memory_order_relaxed和可见性
考虑两个线程,T1 和 T2,它们分别存储和加载一个原子整数 a_i。让我们进一步假设,这家店在执行前正在执行的负荷启动。以前,我的意思是绝对的时间意义。
T1 T2
// other_instructions here... // ...
a_i.store(7, memory_order_relaxed) // other instructions here
// other instructions here // ...
a_i.load(memory_order_relaxed)
// other instructions here
是否保证T2在加载后看到值7?
回答
是否保证T2在加载后看到值7?
内存顺序在这里无关紧要;原子操作是原子的。只要您确保写入“发生在”读取之前(您在问题的前提下声明为真),并且没有其他干预操作,T2 将读取由 T1 写入的值。这是原子操作的本质,内存顺序不会修改这一点。
什么订单存储器控制是如果T2看到7(无论是“之前发生”确保与否),它是否能访问其它由T1修改的数据之前它存储7进入原子。对于relaxed内存排序,T2 没有这样的保证。
注意:您将问题从负载“发生在” store 之后,当 store与 load 明确“同步”时的情况更改为更加模糊的情况。就 C++ 对象模型而言,没有“绝对时间”。特定原子对象上的所有原子操作都按顺序发生,但除非有某些东西在两次加载之间明确创建“发生在/之后”关系,否则无法知道加载了什么值。这将是两种可能性之一,但无法知道哪一种。
-
This is incorrect.. The OP defines 'before' as 'in absolute sense of time'. That does not guarantee that the store is ordered before the load.
By definition, the 2 operations are ordered, but you can only determine the order by evaluating the result of the load.
If the load occurs (let's say) less than a micro second after the store (clock time), it can (and probably will) return the old value due to store buffer effects.