我正在查看有关原子操作和发生前关系的 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];
我的理解是这样的(如有错误请指正)
- 如果 thread2 的
load
操作先于 thread1 的store
操作,则tmp
将是data[0]
。 - 如果thread1的
store
操作先于thread2的load
操作,则tmp
将是data[ 1 ]
因为 thread1 的store(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/