On the x86 architecture, stores to the same memory location have a total order, e.g., see this video. What are the guarantees in the C++11 memory model?
More precise
Per C++11 [intro.multithread]/6: "All modifications to a particular atomic object M
occur in some particular total order, called the modification order of M
." Consequently, reads of an atomic object by a particular thread will never see "older" values than those the thread has already observed. Note that there is no mention of memory orderings here, so this property holds true for all of them - seq_cst
through relaxed
.
In the example given in the OP, the modification order of x
can be either (0,1,2)
or (0,2,1)
. A thread that has observed a given value in that modification order cannot later observe an earlier value. The outcome r1==1, r2==2
implies that the modification order of x
is (0,1,2)
, but r3==2, r4==1
implies it is (0,2,1)
, a contradiction. So that outcome is not possible on an implementation that conforms to C++11 .