在
std::condition_variable
的参考文档中有这个例子:
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
std::mutex m;
std::condition_variable cv;
std::string data;
bool ready = false;
bool processed = false;
void worker_thread()
{
// Wait until main() sends data
std::unique_lock lk(m);
cv.wait(lk, []{ return ready; });
// after the wait, we own the lock.
std::cout << "Worker thread is processing data\n";
data += " after processing";
// Send data back to main()
processed = true;
std::cout << "Worker thread signals data processing completed\n";
// Manual unlocking is done before notifying, to avoid waking up
// the waiting thread only to block again (see notify_one for details)
lk.unlock();
cv.notify_one();
}
int main()
{
std::thread worker(worker_thread);
data = "Example data";
// send data to the worker thread
{
std::lock_guard lk(m);
ready = true;
std::cout << "main() signals data ready for processing\n";
}
cv.notify_one();
// wait for the worker
{
std::unique_lock lk(m);
cv.wait(lk, []{ return processed; });
}
std::cout << "Back in main(), data = " << data << '\n';
worker.join();
}
我的问题非常具体地涉及本节:
{
std::lock_guard lk(m);
ready = true;
std::cout << "main() signals data ready for processing\n";
}
cv.notify_one();
为什么
ready
需要有锁护罩?如果另一个线程正在等待,难道不应该保证 ready = true
在另一个线程被 notify_one
唤醒之前发生吗?
我要求这个问题是为了深入了解一个问题,我看到了一个无法在此处显示的私有代码库。
我更困惑如果ready是一个std::atomic那么锁还需要吗?在私有代码中,我观察到它仍然如此,否则在通知和唤醒发生之前布尔值不会改变
如果没有相关锁,
ready = true;
可能会同时发生(不同步)worker_thread
读取ready
。这是一场数据竞争,并且具有未定义的行为。
你也不知道等待线程何时醒来。它不仅可能被
notify_one
唤醒,还存在虚假唤醒,这就是为什么唤醒后必须检查情况。如果不是true
,请继续等待。