Multicore & Synchronization

In C, why is marking a flag variable shared between threads volatile not sufficient for synchronization?

  1. AA volatile variable can no longer be read by other threads
  2. Bvolatile only restrains compiler optimizations and guarantees neither atomicity nor the order in which other cores see operations
  3. 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.
Practice this topic Back to topic

More Multicore & Synchronization questions

  1. Why do C11 _Atomic and C++11 std::atomic let programmers specify a memory order?
  2. Which correctly compares coarse-grained locking (one lock for a whole large data structure) with fine-grained locking (separate locks for each part)?
  3. What property does a lock-free algorithm have?
  4. Which describes a critical section?
  5. Which describes barrier synchronization in parallel programs?