关于 cppreference 的错误 std::condition_variable 示例?
Wrong std::condition_variable example on cppreference?
在 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...
}
我现在的问题是变量 ready
没有声明 std::atomic*
。
如果发生虚假唤醒,为什么不引入竞争条件?
不,没有竞争条件。
即使条件变量被虚假唤醒,它也必须重新获取锁。因此,会发生两件事:
- 持有锁时,任何线程都不能触及
ready
,因为锁会保护它。
- 通过重新获取锁,布尔值必须同步,因为锁强制执行内存顺序获取,这导致
ready
具有最新值。
所以竞争条件不可能发生。
在 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...
}
我现在的问题是变量 ready
没有声明 std::atomic*
。
如果发生虚假唤醒,为什么不引入竞争条件?
不,没有竞争条件。
即使条件变量被虚假唤醒,它也必须重新获取锁。因此,会发生两件事:
- 持有锁时,任何线程都不能触及
ready
,因为锁会保护它。 - 通过重新获取锁,布尔值必须同步,因为锁强制执行内存顺序获取,这导致
ready
具有最新值。
所以竞争条件不可能发生。