4

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 ?

Cœur
  • 37,241
  • 25
  • 195
  • 267
ashen
  • 807
  • 9
  • 24
  • Be careful. In MT programming, what comes first, later, or immediately is **not** clearly defined. Of course, delayed indefinitely is a clear concept, and so is delayed for ridiculously long. Compilers should make sure neither happens. – curiousguy Jan 07 '20 at 15:02

1 Answers1

8

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.

Anthony Williams
  • 66,628
  • 14
  • 133
  • 155
  • "_A read that does not see the value written must therefore occur earlier in that total order than the write_" How is that different for other orders? – curiousguy Nov 27 '19 at 23:57
  • If your loads use `memory_order_acquire` then if two threads both read both of two different variables `x` and `y`, then they can disagree on the order of a change to `x` relative to a change to `y`. With `memory_order_seq_cst` they must agree. – Anthony Williams Nov 28 '19 at 08:34
  • 1
    Another way to state part of what `seq_cst` guarantees: this store will be visible to other threads *before any other seq_cst operations from this thread*. Which might be achieved in practice with a full memory barrier after a seq_cst store, or by having later seq_cst operations wait, if there are any before this store has a chance to commit to coherent cache (and thus become globally visible.) – Peter Cordes Aug 16 '23 at 17:53
  • 1
    So stronger ordering makes this thread wait before doing other stuff, not pushing stores out any faster. See [Does hardware memory barrier make visibility of atomic operations faster in addition to providing necessary guarantees?](https://stackoverflow.com/q/61591287) for more about that common misconception. – Peter Cordes Aug 16 '23 at 17:53