// Thread 1
// do A
x.store(1, std::memory_order_release); // operation1
// Thread 2
// do B
x.store(2, std::memory_order_release); // operation2
// Thread 3
x.load(std::memory_order_acquire); // operation3
我了解到,如果线程 3 读取线程 1 写入的值,则释放和获取操作同步,A
的效果对线程 3 可见。
但如果情况是这样呢:
x
的修改顺序为1, 2- thread3 读取 thread2 写入的值,因此 2 happens-before 3。
1 和 3 之间是否存在先于关系?
或者从本质上讲,修改顺序是否有助于先于 关系?
最佳答案
没有。操作 1 和操作 3 之间没有 happens-before 关系。
来自 [atomics.order]/2 :
An atomic operation A that performs a release operation on an atomic object M synchronizes with an atomic operation B that performs an acquire operation on M and takes its value from any side effect in the release sequence headed by A.
... 不幸的是,根据 [intro.races]/5,操作 2 不在以操作 1 为首的发布序列中:
A release sequence headed by a release operation A on an atomic object M is a maximal contiguous sub-sequence of side effects in the modification order of M, where the first operation is A, and every subsequent operation is an atomic read-modify-write operation.
因此,我们无法构建任何 inter-thread happens-before relationship在操作 1 和其他操作之间,因此没有 happens-before relationship在操作 1 和操作 3 之间。
关于c++ - 修改顺序是否有助于 happens-before 关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54807379/