gpt4 book ai didi

c++ - cppreference 上的错误 std::condition_variable 示例?

转载 作者:太空狗 更新时间:2023-10-29 20:34:39 28 4
gpt4 key购买 nike

在他们的 example std::condition_variable 本质上的用法

std::mutex m;
std::condition_variable cv;
bool ready = false;

void worker_thread()
{
// Wait until main() sends data
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, []{return ready;});
// more ...
}

int main()
{
std::thread worker(worker_thread);

data = "Example data";
// send data to the worker thread
{
std::lock_guard<std::mutex> lk(m);
ready = true;
}
cv.notify_one();
// more...
}

我现在的问题是未声明 std::atomic* 的变量 ready

如果发生虚假唤醒,为什么这不会引入竞争条件?

最佳答案

不,没有竞争条件。
即使条件变量被虚假唤醒,它也必须重新获取锁。因此,会发生两件事:

  1. 当锁被持有时,任何线程都不能触及 ready,因为锁会保护它。
  2. 通过重新获取锁, bool 值必须同步,因为锁强制执行内存顺序获取,这导致 ready 具有最新值。

所以竞争条件不可能发生。

关于c++ - cppreference 上的错误 std::condition_variable 示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47188883/

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