C++:std::atomic<bool>和 volatile bool [英] C++ : std::atomic<bool> and volatile bool

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

问题描述

我正在阅读 Anthony Williams 的 C++ 并发操作手册.有一个有两个线程的经典示例,一个产生数据,另一个消耗数据,A.W.这段代码写得很清楚:

I'm just reading the C++ concurrency in action book by Anthony Williams. 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;
}

而且我真的不明白为什么这段代码与我使用经典的 volatile 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代替了atomic 有未定义的行为.

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:

读者

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:

两个动作可能同时发生

  • 它们由不同的线程执行,或者
  • 它们是未排序的,并且至少有一个由信号处理程序执行.

如果一个程序包含两个潜在的并发冲突操作,则该程序的执行包含数据竞争,其中至少一个不是原子的,并且都不在另一个之前发生,除了下面描述的信号处理程序的特殊情况.任何此类数据竞争都会导致未定义的行为.

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对这个规则有很大的不同.

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

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

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