Acquire/Release 语义
Acquire/Release semantics
在回答中
@Peter Cordes 写过
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.
我想问一些问题,以便更好地理解它。
我已阅读http://preshing.com/20120913/acquire-and-release-semantics as well. And this article contains:
而且写的是保证r2 == 42
。我不明白为什么。在我看来,这是可能的:
1、Thread2执行了第一行。它是原子的并且是 memory_order_acquire 所以它必须在后续内存操作之前执行。
现在,Thread2 执行第二行:int r2 = A
并且 r2
等于 0
。
然后,Thread1会执行他的代码。
为什么我错了?
完整的报价是:
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.
获取-释放语义只保证
A = 42
不会在线程 1Ready = 1
之后发生
r2 = A
不会在线程 2r1 = Ready
之前发生
所以必须在线程2中检查r1
的值,以确保A
已经被线程1写入。问题中的场景确实可以发生,但是r1
在这种情况下将是 0
。
在回答中
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.
我想问一些问题,以便更好地理解它。
我已阅读http://preshing.com/20120913/acquire-and-release-semantics as well. And this article contains:
而且写的是保证r2 == 42
。我不明白为什么。在我看来,这是可能的:
1、Thread2执行了第一行。它是原子的并且是 memory_order_acquire 所以它必须在后续内存操作之前执行。
现在,Thread2 执行第二行:
int r2 = A
并且r2
等于0
。然后,Thread1会执行他的代码。
为什么我错了?
完整的报价是:
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.
获取-释放语义只保证
A = 42
不会在线程 1Ready = 1
之后发生r2 = A
不会在线程 2r1 = Ready
之前发生
所以必须在线程2中检查r1
的值,以确保A
已经被线程1写入。问题中的场景确实可以发生,但是r1
在这种情况下将是 0
。