文档说可以使用 Predicate 的第二次重载来避免虚假唤醒。我没有看到它,如何修改我的代码以确保 wait_for 不会被虚假唤醒?
while(count_ > 0) {
if (condition_.wait_for(lock, std::chrono::milliseconds(timeOut_)) ==
std::cv_status::timeout)
break;
}
最佳答案
文档具有误导性:可能存在虚假唤醒,但带有谓词的 wait_for()
只会在谓词为 true
时返回。也就是说,当使用谓词版本时,它看起来好像没有虚假唤醒。您可以通过记录谓词执行的频率来检测是否存在虚假唤醒。
你会像这样使用它
if (condition_.wait_for(lock,
std::chrono::milliseconds(timeOut_),
[&](){ return count_ <= 0; }) ==
std::cv_status::timeout) {
// deal with timeout here
}
关于c++ - 忽略虚假唤醒,condition_variable::wait_for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33595917/