Multicore & Synchronization
In C, why is marking a flag variable shared between threads volatile not sufficient for synchronization?
- AA volatile variable can no longer be read by other threads
- Bvolatile only restrains compiler optimizations and guarantees neither atomicity nor the order in which other cores see operations
- CA volatile variable is stored on disk and becomes slow
Show answer and explanation
Answer: B. volatile only restrains compiler optimizations and guarantees neither atomicity nor the order in which other cores see operations
volatile tells the compiler not to omit or merge reads and writes of a variable; it was designed for accessing hardware registers. It does not stop the CPU from reordering memory operations, and it does not make operations such as counter++ atomic. Since C11 and C++11, _Atomic and std::atomic guarantee both atomicity and memory ordering.
- A. Other threads can still read it.
- B. Correct. Use atomic variables for inter-thread synchronization.
- C. It is never stored on disk.