c++ - C++中的condition_variable wait_for

标签 c++ condition-variable unique-lock

我正在Visual Studio 2019上使用condition_variablecondition_variable.wait_for()函数将返回std::cv_status::no_timeout,而无需任何通知。

#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>

std::condition_variable cv;
std::mutex mtx;
bool called = false;

void printThread()
{
    std::unique_lock<std::mutex> lck(mtx);
    while (std::cv_status::timeout == cv.wait_for(lck, std::chrono::seconds(1)))
    {
        std::cout << "*";
    }
    std::cout << "thread exits" << std::endl;
}

int main()
{
    std::thread th(printThread);
    th.join();
    std::cout << "program exits" << std::endl;
}
我认为代码永远不会退出并继续打印*,但是在打印了一些*之后它会退出。
这是输出:
********************************************************************thread exits
program exits
为什么会这样?是所谓的“虚假唤醒”吗?

最佳答案

是的,这是“虚假唤醒”。这在cppreference.com's reference page for wait_for 上进行了解释:

It may also be unblocked spuriously. When unblocked, regardless of the reason, lock is reacquired and wait_for() exits.


翻译:您的计算机中有gremlins。他们偶尔变得脾气暴躁。如果他们确实脾气暴躁,wait_for将在请求的超时时间到期之前返回。当发生这种情况时:

Return value

  1. std::cv_status::timeout if the relative timeout specified by rel_time expired, std::cv_status::no_timeout otherwise.

这似乎正是您所看到的。 C++标准允许C++实现出于任意原因从wait_for过早返回,除非超时到期后wait_for返回,否则no_timeout就是您所获得的。
您可能想知道wait_for(以及其他几个类似的函数)为什么可能决定举手并“虚假地”返回。但这将是一个不同的问题...

关于c++ - C++中的condition_variable wait_for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64929303/

相关文章:

c++ - 使用 std::adopt_lock 选项构造后,std::lock_guard 是否释放互斥锁?

c++ - MINGW 中的 ld exe 找不到库

c++ - std::thread 重载未解决(使用正确的参数)

c++ - 如何验证条件变量是否已初始化?

c - 在没有人等待时发出条件变量信号的意义?

c++11 - 尝试使用 lambda 函数作为 condition_variable 等待方法的谓词

c++ - 通过引用调用 : Use of undeclared identifier

c++ - C++中如何延迟输出?

c++ - 为什么 std::lock() 在使用我自己的 unique_lock 对象时会导致无限循环?

c++ - 将互斥锁引用从 main 传递到类