Abhijit-K
Abhijit-K

Reputation: 3689

Concurrency: C++11 memory model for shared variables in multithreaded environment

If a global variable is shared across 2 concurrently running threads on 2 different cores, is there is possibility of data race or unexpected value even if the access to the shared variable is governed by critical section? Do I need to declare the variable atomic(volatile)? Each core might have a value of the shared variable in its cache and when one threads writes to its copy in a cache the other thread on a different core might read stale value from its cache after thread 1 releases the lock. Do the compiler generate code for volatile read/writes for the variables governed by critical sections or mutex by default?

Upvotes: 3

Views: 1122

Answers (1)

Anthony Williams
Anthony Williams

Reputation: 68671

If all accesses to a shared variable are protected by the same mutex or critical section then this will avoid data races and unexpected values on that variable, even if the threads are on different cores. The lock and unlock functions of the mutex will include the necessary synchronization instructions to ensure that the caches are correctly synchronized across the processor cores. Within the locked region the normal instructions can be used to access the shared variables.

There is no need to declare shared variables as atomic unless you are intending to access them without the protection of a mutex.

Upvotes: 9

Related Questions