在C ++中重新排序原子操作 [英] reordering atomic operations in C++

查看:83
本文介绍了在C ++中重新排序原子操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有2个线程:

int value = 0;
std::atomic<bool> ready = false;

thread 1:
value = 1
ready = true;

thread 2:
while (!ready);
std::cout << value;

该程序能够输出0吗?

我阅读了有关C ++内存模型的信息-具体来说,是顺序一致性,我认为这是默认设置,而且还不是很清楚.只是需要编译器相对于所有其他操作以正确的顺序放置原子操作,还是需要相对于所有其他操作以正确的顺序放置原子操作?

I read about the C++ memory model - specifically, sequential consistency, which I believe is the default, and it wasn't particularly clear. Is the compiler only required to put atomic operations in the correct order relative to each other, or is it required to put atomic operations in the right order relative to all other operations?

推荐答案

默认情况下,对原子变量的默认操作是使用memory_order_seq_cst语义完成的,这保证了不会进行任何重新排序.

By default operations on atomic variables are done using the memory_order_seq_cst semantics, which guarantees that no reordering will be done.

因此,value = 1行无法在原子分配:value = 1下重新排序,因此std::cout << value;行将始终显示1.

Thus the line: value = 1 cannot be reordered below the atomic assignment: value = 1, so the line std::cout << value; will always print 1.

按照相同的规则,以下行:std::cout << value;不能重新排序
在行上方:while (!ready);.

By the same rules, the line: std::cout << value; cannot be reordered
above the line: while (!ready);.

这篇关于在C ++中重新排序原子操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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