c++ - 修改顺序是否有助于 happens-before 关系?

标签 c++ multithreading c++11 atomic happens-before

// 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/

相关文章:

C++ 结构数组 Win Form 损坏

c++ - C++ 中的跨平台网络代码?

ios - 在 iOS 上使用单独的线程联网

sql - 使用TABLOCKX的SQLserver多线程锁定

c++11 - C++ 将 lambda 传递给模板参数

c++ - 不同类型 vector 的 vector

c++ - 为什么返回 *this 会导致无限循环?

Python:多线程不运行

c++ - 重用左值和右值的代码

c++ - 如何将 boost::intrusive_ptr 与 boost::intrusive::list 一起使用?