问题
I command my threads via public accessible member variables that are usually protected by an according mutex.
My question is this: If a single variable is protected by a mutex during write access should it also be protected during read access or can I simply read it?
Example:
A thread checks if something special should be done
(doSpecial is written in another thread)
// some code
if (doSpecial) {
// code
}
// some code
Should this read access be protected by a mutex?
回答1:
Yes, if the variable is modified on one thread and accessed on others, then all accesses must be protected by the mutex. Without that, or some other synchronisation method, there is no guarantee that the modification is atomic (so other threads may read a corrupt value), nor that other threads will see the modified value (it may remain in the cache of one processor and never propagate to others).
In C++11, for simple types, you might consider std::atomic
rather than a non-atomic variable protected by a mutex.
回答2:
I am not sure of that, but it would be very strange that writing a integer or a single boolean is not atomic. I beleive that writing a double (64 bit) is probably atomic too.
If doSpecial is a boolean variable directly accessed by the two threads, you need to qualify it with "volatile". That will prevent the compiler to use a cache for it.
If you don't, the function doing the test ( if (doSpecial) ) may map the variable in a processor internal cache, and the if-test may never see the value change.
Using a mutex doesn't prevent the compiler to do such an optimization on the variable.
A best way to do, would be to access the value by a function :
if ( isSpecial() ) ...
setSpecial( bool ){ ... }
It allows you to add a mutex management in the two functions if they work on more than a single boolean
来源:https://stackoverflow.com/questions/16773515/qmutex-needed-to-read-variable