gpt4 book ai didi

c++ - 宽松原子操作的内存模型释放/获取模式交互

转载 作者:行者123 更新时间:2023-12-04 06:49:41 25 4
gpt4 key购买 nike

GCC Wiki 关于内存模型同步模式是这样说的 Acquire/Release :

To make matters a bit more complex, the interactions of non-atomic variables are still the same. Any store before an atomic operation must be seen in other threads that synchronize. For example:

 -Thread 1- y = 20; x.store (10, memory_order_release); -Thread 2- if (x.load(memory_order_acquire) == 10)    assert (y == 20);
Since 'y' is not an atomic variable, the store to 'y' happens-before the store to 'x', so the assert cannot fail in this case. The optimizers must still limit the operations performed on shared memory variables around atomic operations.

现在,如果我将“y”设为原子变量(不施加happens-before 限制)怎么办?

 -Thread 1-
y.store (20, memory_order_relaxed);
x.store (10, memory_order_release);

-Thread 2-
if (x.load(memory_order_acquire) == 10)
assert (y.load (memory_order_relaxed) == 20);

断言会失败吗?对原子变量的要求是否比对非原子变量的要求少?还是 Wiki 对非原子变量的限制在这里是无端的和误导性的?

最佳答案

Since 'y' is not an atomic variable, the store to 'y' happens-before the store to 'x'

声明“因为 y 不是原子”是不正确的。相同的排序规则适用于原子操作和非原子操作。

获取/释放屏障保证内存操作 A(对 y 的存储)在存储/释放之前排序 happens-before 内存操作 B(断言)在看到存储值的加载/获取之后排序。操作 A 和 B 是否是原子操作无关紧要。
断言 无法触发。

关于c++ - 宽松原子操作的内存模型释放/获取模式交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43491226/

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