Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

多线程中不该牵扯 volatile 关键字,且描述经不起推敲没有逻辑,带有错误暗示 #278

Closed
Mq-b opened this issue May 13, 2024 · 0 comments · Fixed by #281

Comments

@Mq-b
Copy link
Contributor

Mq-b commented May 13, 2024

  • 文件路径:book/zh-cn/07-thread

原文:

7.5 原子操作与内存模型

细心的读者可能会对前一小节中生产者消费者模型的例子可能存在编译器优化导致程序出错的情况产生疑惑。 例如,布尔值 notified 没有被 volatile 修饰,编译器可能对此变量存在优化,例如将其作为一个寄存器的值, 从而导致消费者线程永远无法观察到此值的变化。

notified 为一个标志位,定义在上文,如下:

bool notified = false;  // 通知信号

C++11 ISO 标准代码中的 volatile 关键字仅用于硬件访问,不该用作多线程中。在本文中,虽然它勉强与标题有点关系,但是这个例子并不合适。并且在我看来有其错误的暗示暗示 volatile 在多线程环境中使用它是有意义的

见微软文档

The volatile keyword in C++11 ISO Standard code is to be used only for hardware access; do not use it for inter-thread communication. For inter-thread communication, use mechanisms such as std::atomic from the C++ Standard Library.

cppreference

易变对象 是以下对象之一:
类型具有 volatile 限定的对象
易变对象的子对象
常量易变对象的可变子对象
每次访问(读或写、调用成员函数等)易变类型之泛左值表达式,都当作优化方面可见的副作用(即在单个执行线程内,易变对象访问不能被优化掉,或者与另一先于或后于该易变对象访问的可见副作用进行重排序。这使得易变对象适用于与信号处理函数而非另一执行线程交流,参阅 std::memory_order)。试图通过非易变类型的泛左值访问易变对象(例如,通过到非易变类型的引用或指针)的行为未定义。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
1 participant