3

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?

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the nice explanation. After reading stories of compiler optimization and new memory model just wanted to confirm. One more question is after removing critical section, if I declare shared variable as atomic as only concern is to read a correct, valid value. With atomic declaration is there still a possibility of other thread reading stale (but valid) value? Or the compiler does strong memory ordering to read the latest value(volatile read) from the other cache?
@AbhijitKadam, that's a whole new question actually. Stale values and synchronizes-with relationships using atomics are bit more complex than mutexes.
This is a complex issue. Yes, there is the possibility of reading stale values, but by default there is a single total order of atomic accesses, so this shouldn't cause a problem. BTW, volatile accesses are entirely independent of atomic operations, and do not affect memory ordering. If you want to know about atomic operations, post a new question.
@Anthony,Created another one. Waiting for your expert opinion stackoverflow.com/questions/8819095/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.