C ++:std :: atomic< bool>和挥发性沸石 [英] C++ : std::atomic<bool> and volatile bool

查看:101
本文介绍了C ++:std :: atomic< bool>和挥发性沸石的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在Anthony Williams的动作书中阅读C ++并发。
有两个线程的典型示例,一个产生数据,另一个消耗数据和A.W.写的代码很清楚:

I'm just reading the C++ concurrency in action book by Anthony Williams. And there is this classic example with two threads, one produce data, the other one consumes the data and A.W. wrote that code pretty clear :

std::vector<int> data
std::atomic<bool> data_ready(false)

void reader_thread()
{
    while(!data_ready.load())
    {
        std::this_thread::sleep(std::milliseconds(1));
    }
    std::cout << "The answer=" << data[0] << "\n";
}

void writer_thread()
{
    data.push_back(42);
    data_ready = true;
}



我真的不明白为什么这个代码不同于' d使用经典的波动bool而不是原子。
如果有人可以打开我的主题,我会感激。
感谢。

And i really don't understand why this code differs from one where i'd use a classic volatile bool instead of the atomic one. If someone could open my mind on the subject, i'd be grateful. Thanks.

推荐答案

最大的区别是这个代码是正确的,而版本 bool 而不是原子< bool> 有未定义的行为。

The big difference is that this code is correct, while the version with bool instead of atomic<bool> has undefined behavior.

的代码创建了一个竞争条件(形式上,一个冲突),因为它们读取和写入同一个变量:

These two lines of code create a race condition (formally, a conflict) because they read from and write to the same variable:


读者

Reader

while (!data_ready)

和作者

data_ready = true;


正常变量上的竞争条件会导致未定义的行为,根据到C ++ 11内存模型。

And a race condition on a normal variable causes undefined behavior, according to the C++11 memory model.

规则在标准的第1.10节中找到,最相关的是:

The rules are found in section 1.10 of the Standard, the most relevant being:


如果

Two actions are potentially concurrent if


  • 它们由不同的线程执行,

执行如果一个程序包含两个潜在并发的冲突动作,其中至少有一个不是原子的,并且不是在另一个之前发生,除了下面描述的信号处理器的特殊情况之外,程序包含数据竞争。任何这样的数据竞争导致未定义的行为。

The execution of a program contains a data race if it contains two potentially concurrent conflicting actions, at least one of which is not atomic, and neither happens before the other, except for the special case for signal handlers described below. Any such data race results in undefined behavior.

您可以看到变量是否 atomic< bool> 这个规则有很大的区别。

You can see that whether the variable is atomic<bool> makes a very big difference to this rule.

这篇关于C ++:std :: atomic&lt; bool&gt;和挥发性沸石的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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