std :: atomic会阻止非原子变量对原子变量进行重新排序 [英] Does std::atomic prevent reordering of nonatomic variables over the atomic variables

查看:131
本文介绍了std :: atomic会阻止非原子变量对原子变量进行重新排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题很简单问: 如果我有

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
}

标准是否保证A行不会在B行之后重新排序? STNGS的用户还会始终看到一致的数据吗(如在内存可见性中所承诺的那样)?

does standard guarantee that line A wont be reordered after line B? Also will users of STNGS always see consistent(commited-as in memory visibility visible) data?

对于多个读取器线程和非平凡的设置,与简单的静音相比,这值得麻烦吗?

for multiple reader threads and nontrivial settings is this worth the trouble compared to simple mutexing?

推荐答案

给出定义

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

和线程1正在执行:

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

和线程2正在执行:

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

然后是的,如果第X行的线程2读取了B行中的线程1编写的new_settings,并且对settings[new_settings]没有其他修改(通过一些我们未看到的代码),则线程2绑定到读取somevalue,并且不会发生未定义的行为.这是因为所有操作(默认情况下)都是memory_order_seq_cst,并且释放写入(行B)与获取读取(行X)同步.请注意,您需要在线程2中使用两条语句来获得索引的原子读取与值读取之间的先序关系(memory_order_consume操作将代替).

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. 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). 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).

我肯定会使用rw-mutexes来实现它.

I'd certainly implement it with rw-mutexes for start.

这篇关于std :: atomic会阻止非原子变量对原子变量进行重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆