[英]Does memory_order_relaxed respect data dependencies within the same thread?
Given:鉴于:
std::atomic<uint64_t> x;
uint64_t f()
{
x.store(20, std::memory_order::memory_order_relaxed);
x.store(10, std::memory_order::memory_order_relaxed);
return x.load(std::memory_order::memory_order_relaxed);
}
Is it ever possible for f
to return a value other than 10
, assuming there is only one thread writing to x
?假设只有一个线程写入
x
, f
是否有可能返回10
以外的值? This would obviously not be true for a non-atomic variable, but I don't know if relaxed is so relaxed that it will ignore data dependencies in the same thread?对于非原子变量,这显然不是真的,但我不知道放松是否如此放松以至于它会忽略同一线程中的数据依赖性?
The result of the load is always 10 (assuming there is only one thread).加载的结果总是 10(假设只有一个线程)。 Even a relaxed atomic variable is "stronger" than a non-atomic variable:
即使是松弛的原子变量也比非原子变量“更强”:
A relaxed atomic variable can't be used to synchronize different threads with each other, unless accompanied by explicit fences.除非伴随显式栅栏,否则不能使用宽松的原子变量来使不同的线程彼此同步。 That's the sense in which it's relaxed, compared with the other memory orderings that are applicable to atomic variables.
与适用于原子变量的其他内存排序相比,这就是它放松的感觉。
For language lawyering, see C++20 [intro.races]/10:对于语言律师,请参阅 C++20 [intro.races]/10:
An evaluation A happens before an evaluation B (or, equivalently, B happens after A ) if:
在以下情况下,评估A发生在评估B之前(或等效地, B发生在A之后):
- A is sequenced before B , or [...]
A在B之前排序,或 [...]
and [intro.races]/15:和 [intro.races]/15:
If an operation A that modifies an atomic object M happens before an operation B that modifies M , then A shall be earlier than B in the modification order of M .
如果修改原子对象M的操作A发生在修改M的操作B之前,则A在M的修改顺序中应早于B。 [ Note: This requirement is known as write-write coherence.
[注意:此要求称为写-写一致性。 — end note ]
—尾注]
and [intro.races]/18:和 [intro.races]/18:
If a side effect X on an atomic object M happens before a value computation B of M , then the evaluation B shall take its value from X or from a side effect Y that follows X in the modification order of M .
如果在原子物体M的副作用X M的值计算B之前发生,则评价乙应采取从X或从副作用ý下面X在M的修改次序它的值。 [ Note: This requirement is known as write-read coherence.
[注意:此要求称为读写一致性。 — end note ]
—尾注]
Thus, in your program, the store of 20 happens before the store of 10 (since it is sequenced before it) and the store of 10 happens before the load.因此,在您的程序中,20 的存储发生在 10 的存储之前(因为它在它之前排序)并且 10 的存储发生在加载之前。 The write-write coherence requirement guarantees that the store of 10 occurs later in the modification order of
x
than the store of 20. When the load occurs, it is required to take its value from the store of 10, since the store of 10 happens before it and there is no other modification that can follow the store of 10 in the modification order of x
.写写一致性要求保证 10 的存储发生在
x
的修改顺序上比 20 的存储晚。 当加载发生时,需要从 10 的存储中取其值,因为 10 的存储发生在它之前,没有其他修改可以按照x
的修改顺序跟随 10 的存储。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.