![](/img/trans.png)
[英]Is it right to use std::condition_variable::wait inside a while loop?
[英]while loop for condition_variable
在以下示例中,我不了解ready
的目的。 在此示例中,使用或不使用ready
有什么区别?
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void print_id (int id) {
std::unique_lock<std::mutex> lck(mtx);
while (!ready) cv.wait(lck);
// ...
std::cout << "thread " << id << '\n';
}
void go() {
std::unique_lock<std::mutex> lck(mtx);
ready = true;
cv.notify_all();
}
int main ()
{
std::thread threads[10];
// spawn 10 threads:
for (int i=0; i<10; ++i)
threads[i] = std::thread(print_id,i);
std::cout << "10 threads ready to race...\n";
go(); // go!
for (auto& th : threads) th.join();
return 0;
}
原因是cv.wait(lck);
由于称为“虚假唤醒”的事件,可以在进行 notify_all
调用之前返回。 您会看到“ 虚假唤醒”的解释听起来像是一个不值得修复的错误,对吗? 有关此原因的更多信息。
因此,等待/通知线程使用一个附加的谓词(在这种情况下ready
)来发信号通知该条件是否已发出信号或该条件是否由于虚假唤醒而唤醒。
如果没有ready
( ready
为false),您将阻塞一个或多个线程,直到调用其中一个或所有线程,然后让它们完成工作为止。 但是,当ready
为true时,您将不会阻塞任何线程。 这很重要,因为没有ready
标志,您可能会阻塞应执行的线程,因此将没有信息让它再次运行(当您阻塞线程时,您必须通知它,否则它将永远等待)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.