且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C++:std::atomic<bool>和 volatile bool

更新时间:2022-06-22 02:40:56

最大的不同是这段代码是正确的,而版本用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.