gpt4 book ai didi

c++ - 使用 volatile bool 变量进行忙等待

转载 作者:行者123 更新时间:2023-11-30 04:12:08 25 4
gpt4 key购买 nike

在阅读了其他开发人员编写的一些代码后出现了这个问题,所以我做了一些研究,发现了 Andrei Alexandrescu 的文章。在他的article他说可以使用 volatile bool 变量进行忙等待(参见第一个等待/唤醒示例)

class Gadget
{
public:
void Wait()
{
while (!flag_)
{
Sleep(1000); // sleeps for 1000 milliseconds
}
}
void Wakeup()
{
flag_ = true;
}
...
private:
bool flag_;
};

我真的不明白它是如何工作的。

  1. volatile 不保证操作是原子的。实际上,对 bool 变量的读/写是原子的,但理论并不能保证这一点。在我看来,上面的代码可以通过使用 std::atomic::load/store 函数和相应的获取/释放内存排序约束,用 C++11 安全地重写。
  2. 我们在描述的示例中没有这个问题,但是如果我们有超过一次的写入,我们可能会遇到内存排序问题。 Volatile 不是栅栏,它不强制内存排序,它只是阻止编译器优化。

那么为什么这么多人使用 volatile bool 来进行忙等待,它真的可以移植吗?

最佳答案

这篇文章并没有说 volatile 就是您所需要的(事实上,它不是),只是说它很有用。

If you do this, and if you use the simple generic component LockingPtr, you can write thread-safe code and worry much less about race conditions, because the compiler will worry for you and will diligently point out the spots where you are wrong.

关于c++ - 使用 volatile bool 变量进行忙等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19933422/

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