什么C ++ 11< atomic>操作/内存订单可确保新鲜度? [英] What C++11 <atomic> operations/memory orders guarantees freshness?
问题描述
可能重复:
并发性:C ++ 11内存模型中的原子和易失性
Possible Duplicate:
Concurrency: Atomic and volatile in C++11 memory model
使用C ++ 11 <atomic>
规范,是否可以保证新鲜度?对不同内存顺序的描述仅涉及重新排序(据我所知).
With the C++11 <atomic>
specification, is there any guarantee of freshness? The descriptions of different memory orders only deal with reorderings (as far as I've seen).
特别是在这种情况下:
#include <atomic>
std::atomic<int> cancel_work(0);
// Thread 1 is executing this function
void thread1_func() {
...
while (cancel_work.load(<some memory order>) == 0) {
...do work...
}
}
// Thread 2 executes this function
void thread2_func() {
...
cancel_work.store(1, <some memory order>);
...
}
如果线程1和线程2除cancel_work
以外不共享任何其他数据,在我看来,不需要任何排序保证,并且std::memory_order_relax
足以满足存储和装载需求.但这是否保证线程1能够看到cancel_work
的更新,而不是仅仅重复读取其本地缓存行而不必从主内存中刷新它?如果没有,那么做出保证的最低要求是什么?
If thread 1 and thread 2 do not share any other data except cancel_work
, it seems to me that any ordering guarantees are not needed and std::memory_order_relax
suffices for both the store and the load. But does this guarantee that thread 1 will ever see the update of cancel_work
instead of just repeatedly reading its local cache line without ever refreshing it from main memory? If not, what is the minimum needed to make that guarantee?
推荐答案
没有什么可以保证:一切都与订购有关.甚至memory_order_seq_cst
都可以保证事情以单个总顺序发生.从理论上讲,编译器/库/cpu可以在程序结束时调度cancel_store
中的每次加载.
There is nothing that will guarantee that: everything is about ordering. Even memory_order_seq_cst
just guarantees that things happen in a single total order. In theory, the compiler/library/cpu could schedule every load from cancel_store
at the end of the program.
29.3p13中有一个一般性声明
There is a general statement in 29.3p13 that
实施应使原子存储在合理的时间内对原子负载可见.
Implementations should make atomic stores visible to atomic loads within a reasonable amount of time.
但是没有关于什么构成合理的时间"的规定.
But there is no specification on what constitutes a "reasonable amount of time".
因此:memory_order_relaxed
应该很好,但是memory_order_seq_cst
在某些平台上可能会更好,因为可能会更快地重新加载缓存行.
So: memory_order_relaxed
should be just fine, but memory_order_seq_cst
may work better on some platforms, as the cache line may be reloaded sooner.
这篇关于什么C ++ 11< atomic>操作/内存订单可确保新鲜度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!