Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Acquire/Release semantics

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: enter image description here

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.

  1. Now, Thread2 executes the second line: int r2 = A and r2 equals to 0.

  2. Then, Thread1 will execute his code.

Why am I wrong?

like image 425
Gilgamesz Avatar asked Jul 18 '16 13:07

Gilgamesz


1 Answers

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 1
  • r2 = A doesn't happen before r1 = Ready in thread 2

So 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.

like image 78
alain Avatar answered Sep 19 '22 12:09

alain