PDA

View Full Version : single variable and QMutex



babu198649
7th December 2008, 04:48
hi
Is it necessary to protect a single variable with mutex when only a single variable is getting changed.

drhex
8th December 2008, 10:06
Yes, a statement such as


foo++;

can in the object code expand to several instructions. Pseudocode:



register = foo;
register += 1;
foo = register;

If another thread is also executing the same instructions, it may have been interrupted right after the first pseudo-instruction above. The variable will then be incremented only once even when two threads tried to increment it...

babu198649
9th December 2008, 05:59
Thanks
Does changing a boolean value also takes more than one instruction.

drhex
9th December 2008, 08:45
Not if you're simply assigning true or false to it.

But bools rarely come alone. They might, say, indicate that some data structure is ready for use (which should then also be protected by the mutex).

If another thread needs to QWaitCondition for the bool to have a particular value, it will need a mutex argument.