我正在Visual Studio 2019上使用condition_variable
。condition_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
- 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/