简体   繁体   English

std :: atomic是否阻止对原子变量重新排序非原子变量

[英]Does std::atomic prevent reordering of nonatomic variables over the atomic variables

question is rather simple Q: If I have 问题很简单问:如果我有

settings[N_STNGS];//used by many threads  
std::atomic<size_t> current_settings(0);
void updateSettings()//called by single thread  , always the same thread if that is important
{

    auto new_settings = (current_settings+1)%N_STNGS;
    settings[new_settings].loadFromFileSystem(); //line A
    current_settings=new_settings; //line B
}

does standard guarantee that line A wont be reordered after line B? 标准保证A行不会在B行后重新排序吗? Also will users of STNGS always see consistent(commited-as in memory visibility visible) data? STNGS的用户是否也会始终看到一致(提交内存可见性可见)数据?

Edit: for multiple reader threads and nontrivial settings is this worth the trouble compared to simple mutexing? 编辑:对于多个读者线程和非平凡的设置这是否值得麻烦与简单的静音相比?

Given the definition 鉴于定义

int settings[N_STNGS];
std::atomic<size_t> current_settings(0);

and Thread 1 executing: 和线程1执行:

settings[new_settings] = somevalue;  // line A
current_settings=new_settings;       // line B

and Thread 2 executing: 和线程2执行:

int cur_settings = current_settings;        // line X
int setting_value = settings[cur_settings]; // line Y

then yes, if Thread 2 at line X reads new_settings written by Thread 1 in line B, and there are no other modifications to settings[new_settings] (by some code we don't see), Thread 2 is bound to read somevalue and no undefined behavior occurs. 然后是,如果线程2的行X读取new_settings由线程1中的线B写的,并且不存在其他的修改,以settings[new_settings]由一些代码我们看不到),线程2被绑定到读somevalue和无发生未定义的行为。 This is because all the operations are (by default) memory_order_seq_cst and a release-write (line B) synchronizes with an acquire-read (line X). 这是因为所有操作(默认情况下)是memory_order_seq_cst ,释放 - 写入(行B)与获取读取(行X)同步。 Note that you need two statements in Thread 2 to get a sequenced-before relationship between the atomic read of the index and the read of the value (a memory_order_consume operation would do instead). 请注意,您需要在线程2中使用两个语句来获取索引的原子读取和值的读取之间的顺序排序关系(而memory_order_consume操作将执行memory_order_consume操作)。

I'd certainly implement it with rw-mutexes for start. 我肯定会用rw-mutex来实现它。

The general answer is no. 一般的答案是否定的。 If you are careful and you use only functions which have a memory_order parameter and pass them the right value for it depending on what you are doing, then it may be yes. 如果你小心并且只使用具有memory_order参数的函数并根据你正在做的事情为它传递正确的值,那么它可能是肯定的。

(And as other have pointed out, your code has problems. For instance, returning by value an atomic<> type doesn't make sense for me.) (正如其他人所指出的,你的代码有问题。例如,按值返回原子<>类型对我来说没有意义。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM