Search code examples
c++multithreadingc++11atomic

Does seq_cst ordering guarantee immediate visibility?


N3243 1.10.21 says

It can be shown that programs that correctly use mutexes and memory_order_ seq_cst operations to prevent all data races and use no other synchronization operations behave as if the operations executed by their constituent threads were simply interleaved, with each value computation of an object being taken from the last side effect on that object in that interleaving. This is normally referred to as “sequential consistency”.

Does this mean that any seq_cst writes on an atomic object are immediately visible to other threads which read the atomic object with seq_cst ordering ?


Solution

  • No, there is nothing in the C++ standard that guarantees immediate visibility.

    Atomic writes should become visible to other threads within a "reasonable" period of time, but they do not have to be immediate, and there is no precise definition of "reasonable".

    What is guaranteed is that there is a single total order of memory_order_seq_cst operations. A read that does not see the value written must therefore occur earlier in that total order than the write. Since this total order encompasses all variables and all memory_order_seq_cst operations, if there is any communication between the threads at all, then writes must become visible pretty quickly.