In the answer StoreStore reordering happens when compiling C++ for x86 @Peter Cordes has written
For Acquire/Release semantics to give you the ordering you want, the last store has to be the release-store, and the acquire-load has to be the first load. That's why I made y a std::atomic, even though you're setting x to 0 or 1 more like a flag.
I would like to ask some questions to better understand it.
I have read http://preshing.com/20120913/acquire-and-release-semantics as well. And this article contains:
And it is written that it is ensured that r2 == 42
. I don't understand why. On my eye it is possible:
1. Thread2 executed the first line. It is atomic and it is memory_order_acquire so it must be executed before following memory operations.
Now, Thread2 executes the second line:
int r2 = A
andr2
equals to0
.Then, Thread1 will execute his code.
Why am I wrong?