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"?
while
loop.wait_for
should always returnstd::cv_status::timeout
since notification is not triggered. – Macedoinenotify_xx
is never called so it has to always timeout. – Macedoine