[Qt-interest] How to make a variable (primitive, object or pointer to something) thread safe ?

Sean Harmer sean.harmer at maps-technology.com
Sun Aug 23 11:58:25 CEST 2009


Hi,

On Sunday 23 Aug 2009 10:08:34 Patric wrote:
> Hi guys,
> is there a way to make a class member (primitive variable, an object or
> just a pointer) thread safe ? I know that QMutex is used to synchronize
> some code block, but is there any way to do it for a single variable ?
Think of the mutex as protecting the data in the code block not as protecting 
the code block. It then follows that you need to use your mutex everywhere 
that you can read or write to your variable. Take a look at the mandelbrot 
example for a typical pattern of protecting the member variables of a class. 
Notice how in the run() function the member variables are copied into local 
variables (whilst holding the mutex). This is so that the mutex can be 
unlocked as soon as possible so as not to block the main thread.

HTH,

Sean



More information about the Qt-interest-old mailing list