From 5c50dbc591b045e3633fbe957c7702e483664566 Mon Sep 17 00:00:00 2001 From: "A. Jiang" Date: Tue, 21 May 2024 05:56:11 +0800 Subject: [PATCH] book: avoid implication that `volatile` may be usable in concurrency (#281) --- book/en-us/07-thread.md | 2 +- book/zh-cn/07-thread.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/book/en-us/07-thread.md b/book/en-us/07-thread.md index 379d4d2..14f7406 100644 --- a/book/en-us/07-thread.md +++ b/book/en-us/07-thread.md @@ -228,7 +228,7 @@ We simply can't expect multiple consumers to be able to produce content in a par ## 7.5 Atomic Operation and Memory Model Careful readers may be tempted by the fact that the example of the producer-consumer model in the previous section may have compiler optimizations that cause program errors. -For example, the boolean `notified` is not modified by `volatile`, and the compiler may have optimizations for this variable, such as the value of a register. +For example, the compiler may have optimizations for the variable `notified`, such as the value of a register. As a result, the consumer thread can never observe the change of this value. This is a good question. To explain this problem, we need to further discuss the concept of the memory model introduced from C++11. Let's first look at a question. What is the output of the following code? ```cpp diff --git a/book/zh-cn/07-thread.md b/book/zh-cn/07-thread.md index 8e11407..c32a3c6 100644 --- a/book/zh-cn/07-thread.md +++ b/book/zh-cn/07-thread.md @@ -232,7 +232,7 @@ int main() { ## 7.5 原子操作与内存模型 细心的读者可能会对前一小节中生产者消费者模型的例子可能存在编译器优化导致程序出错的情况产生疑惑。 -例如,布尔值 `notified` 没有被 `volatile` 修饰,编译器可能对此变量存在优化,例如将其作为一个寄存器的值, +例如,编译器可能对变量 `notified` 存在优化,例如将其作为一个寄存器的值, 从而导致消费者线程永远无法观察到此值的变化。这是一个好问题,为了解释清楚这个问题,我们需要进一步讨论 从 C++ 11 起引入的内存模型这一概念。我们首先来看一个问题,下面这段代码输出结果是多少? @@ -242,7 +242,7 @@ int main() { int main() { int a = 0; - int flag = 0; + volatile int flag = 0; std::thread t1([&]() { while (flag != 1);