http://en.cppreference.com/w/cpp/atomic/memory_order has a good example at the bottom that only works with memory_order_seq_cst
. Essentially memory_order_acq_rel
provides read and write orderings relative to the atomic variable, while memory_order_seq_cst
provides read and write ordering globally. That is, the sequentially consistent operations are visible in the same order across all threads.
The example boils down to this:
bool x= false;
bool y= false;
int z= 0;
a() { x= true; }
b() { y= true; }
c() { while (!x); if (y) z++; }
d() { while (!y); if (x) z++; }
// kick off a, b, c, d, join all threads
assert(z!=0);
Operations on z
are guarded by two atomic variables, not one, so you can't use acquire-release semantics to enforce that z
is always incremented.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…