How std::memory_order_seq_cst works
Because read-modify-write operations have special guarantees.
According to the standard [atomics.order] paragraph 11:
Atomic read-modify-write operations shall always read the last value (in the modification order) written before the write associated with the read-modify-write operation.
So by seeing different things in your comment you mean that Thread C see x==1,y==0 and Thread D see x==0 and y==1. Is that possible with sequential consistency?
Let's suppose this total order (the modification is the transition between this symbolized memory states):
{x==0,y==0} : S0
{x==1,y==0} : S1
{x==1,y==1} : S2
When we say "see" we mean that a thread potentialy performs a load. Two loads can not be performed simultaneously in one thread. So how is it possible that thread C see x==1 then see y==0 and Thread D see x==0 then see y==1? Thread C performs the two loads while the memory is in the state S1, and Thread D see x
at state S0, then see y
at state S2.
In your example code, what happens is that Thread C load x then load y, and Thread D load y repeatedly until it is true then load x. So after y==1, it is guarenteed that x==1
in this total order.
As said by Minee in its comment, nothing could be expected if in place of sequential consistency memory order were used acquire/release memory order: acquire/release semantic does not imply any total ordering,moreover there are no happens before relation between the store to x
and the store to y
. So the assertion z.load()!=0
could fire.