gpt4 book ai didi

c++ - boost memory_order_consume 示例

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:27:41 26 4
gpt4 key购买 nike

我正在查看有关原子操作和发生前关系的 Boost 示例,但我有点困惑。在“通过发布和消费发生之前”部分,有以下示例,他们说这是错误的,但我看不到:

atomic<int> a(0);
complex_data_structure data[2];

线程 1:

      data[1] = ...; /* A */
a.store(1, memory_order_release);

线程 2:

      int index = a.load(memory_order_consume);
complex_data_structure tmp;
if (index == 0)
tmp = data[0];
else
tmp = data[1];

Boost Example

我的理解是这样的(如有错误请指正)

  1. 如果 thread2load 操作先于 thread1store 操作,则 tmp 将是 data[0]
  2. 如果thread1store操作先于thread2load操作,则tmp 将是 data[ 1 ] 因为 thread1store(1,memory_order_release) 将确保所有先前写入其他内存位置对 thread2 可见,即使 data[] 在计算上不依赖于索引。

有人可以澄清他们正在谈论的错误吗?

最佳答案

使用release/consume,在store(release)之前写入变量仅保证在匹配的 load(consume) 时可见 当且仅当变量取决于在store(release)-load(consume) 对。

通过使用 int 文字来索引 data[] 这种依赖性已经被打破,因此写入 data[] 不能保证在a.load(消费)

关于c++ - boost memory_order_consume 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16667246/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com