On 29/08/2014 00:53, firespot wrote:
How does memory synchronization and visibility behave when multiple mutexes are involved?
It's typically safe to assume that both locking and unlocking generate a compiler fence, so the compiler is not allowed to move reads or writes from after a mutex acquire to before it, or from before a mutex release to after it. In practice it shouldn't move code outside of the guarded block to inside it, either. This is irrespective of what actual mutexes are involved, as the compiler and processor are not aware of the relationship between mutexes and their protected variables -- that's a conceptual thing only.
{ boost::unique_lockboost::mutex Lock(m1); Ptr = someAddress; // set the Ptr from 0 to some memory address }
Provided that exactly one of each of f() and g() can be run concurrently (and there's no other code that messes with these variables), then this lock is actually unnecessary. g() will block on m2 waiting for run to be set, and so there is no possible race on Ptr in this case (assuming that run is always initially false). Things do get hairier (and the code you provided will get in trouble) if it is possible for there to be more than one instance of either function running concurrently on the same variables.