I am working with condition_variable on Visual studio 2019. The condition_variable.wait_for() function returns std::cv_status::no_timeout without any notification.
#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;
}
I think the code will never exit and keep printing *, but it exits after printing some *.
Here is the output:
********************************************************************thread exits
program exits
Why does this happen? Is it the so-called "spurious wakeups"?
Yes, it's a "spurious wakeup". This is explained on cppreference.com's reference page for
wait_for:Translation: there are gremlins in your computer. They get grumpy, occasionally. And if they do get grumpy,
wait_forreturns before the requested timeout expires. And when that happens:And that seems to be exactly what you're seeing. The C++ standard permits a C++ implementation to return from
wait_forprematurely, for arbitrary reasons, and unless you do return fromwait_forwhen the timeout expires,no_timeoutis what you get.You might be wondering why
wait_for(and several other similar functions) may decide to throw up their hands and return "spuriously". But that would be a different question...