gpt4 book ai didi

c++ - 为什么 volatile 会产生未定义的行为

转载 作者:搜寻专家 更新时间:2023-10-30 23:53:15 24 4
gpt4 key购买 nike

据我理解,volatile限定值意味着无论何时访问它,我们都必须去地址处取最新的值。

现在我正在阅读 Effective Modern C++ 这本书,但我不明白为什么 volatile 会在这里生成 UB:

volatile int vi(0); // initialize vi to 0
vi = 10; // set vi to 10
std::cout << vi; // read vi's value
++vi; // increment vi to 11
vi--; // decrement vi to 10

During execution of this code, if other threads are reading the value of vi, they may see anything (e.g, -12, 68, 4090727—anything!). Such code would have undefined behavior, because these statements modify vi, so if other threads are reading vi at the same time, there are simultaneous readers and writers of memory that’s neither std::atomic nor protected by a mutex, and that’s the definition of a data race.



在我看来,如果其他线程可能看到 0、10 或 11,我可以理解,但为什么书上说“他们可能看到任何东西”?

最佳答案

本节讨论的是 volatile 对于多线程编程是安全的常见误解。如果不同的线程同时读取和写入 vi,那么就会发生数据竞争,因为没有适当的同步或原子性保证。数据竞争是 C++ 中的未定义行为,因此“任何东西”确实意味着任何东西。

如果改为使用正确的原子操作,则可以保证对 vi 的所有修改都不会被其他线程中断,因此您将不会发生数据竞争,您的程序将是安全的。或者,可以使用互斥锁或类似方式引入同步。

请参阅 this site 中的引用资料有关为什么 volatile 对这种事情不安全的更多详细信息。

关于c++ - 为什么 volatile 会产生未定义的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41977723/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com