c++ - 忽略虚假唤醒,condition_variable::wait_for

标签 c++ c++11 condition-variable

文档说可以使用 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/

相关文章:

c++ - 将 boost spirit 用于基于堆栈的语言

c++ - 如何在 Linux 下安装 Haskell? - 官方文档中的错误?

c++ - gcc constexpr 解释为内联?

c++ - 在 clang 格式的控制语句之后中断

c++ - 终止正在运行的线程 c++ std::thread

c++ - Qt永久线程

c++ - 使用 static_assert 确保模板参数只*最多*一次使用

C++11 线程 : Multiple threads waiting on a condition variable

c++ - std::condition_variable::wait_until 如何工作

c++ - 如何在生产者-消费者场景中使用 Boost 条件变量?