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
and r2
equals to 0
.
Then, Thread1 will execute his code.
Why am I wrong?
The complete quote is:
If we let both threads run and find that r1 == 1, that serves as confirmation that the value of A assigned in Thread 1 was passed successfully to Thread 2. As such, we are guaranteed that r2 == 42.
The aquire-release semantics only guarantee that
A = 42
doesn't happen after Ready = 1
in thread 1r2 = A
doesn't happen before r1 = Ready
in thread 2So the value of r1
has to be checked in thread 2 to be sure that A
has been written by thread 1. The scenario in the question can indeed happen, but r1
will be 0
in that case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With