I am trying to understand the difference between memory_order_seq_cst and memory_order_acq_rel. A few posts on SO already covered this question, however, I don't understand their answer.
This post said
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.
It also includes an example
bool x= false;
bool y= false;
bool 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);
The snippet is a skeleton version of an example on cppreference.com. I compiled the example on Ideone and CoLiRu. On Ideone, z could be 1 or 2 under both memory_order_acq_rel and memory_order_seq_cst. On CoLiRu, I could only get 2. It's never 0.
My questions are:
- Don't while(!x) and while(!y) guarantees that either if(y) or if(x) returns true, even we use per atomic variable ordering?
- How does this example explain the difference between memory_order_acq_rel and memory_order_seq_cst?
- Can anyone provide an example using memory fence to illustrate the difference between per atomic variable ordering and global ordering?