Search code examples
c++multithreadingmemory-modelstdatomic

reordering atomic operations in C++


Suppose I have 2 threads:

int value = 0;
std::atomic<bool> ready = false;

thread 1:
value = 1
ready = true;

thread 2:
while (!ready);
std::cout << value;

Is this program able to output 0?

I read about the C++ memory model - specifically, sequential consistency, which I believe is the default, and it wasn't particularly clear. Is the compiler only required to put atomic operations in the correct order relative to each other, or is it required to put atomic operations in the right order relative to all other operations?


Solution

  • By default operations on atomic variables are done using the memory_order_seq_cst semantics, which guarantees that no reordering will be done.

    Thus the line: value = 1 cannot be reordered below the atomic assignment: value = 1, so the line std::cout << value; will always print 1.

    By the same rules, the line: std::cout << value; cannot be reordered
    above the line: while (!ready);.