Acquire/Release semantics
Asked Answered
A

1

6

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?

Augusto answered 18/7, 2016 at 13:15 Comment(0)
S
9

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.

Si answered 18/7, 2016 at 13:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.