like my code, and i learn in https://en.cppreference.com/w/cpp/thread/condition_variable, my question is why i remove lock_guard with task++; then result is wait timeout. i learned, wait check task is 0, then unlock and to wait, but before wait, thread2 run finish task++ and notify, so cause Lost wake-up problem?
so i think should to lock task++ and cv.notify_all(); otherwise, Unable to solve Lost wake-up problem? but in cppreference example, unlock before notify_all, to avoid the waiting thread only to block again.
unlock+wait, wakeup, and lock
wait_for is lock , check, wait, unlock? recv notify is wakeup + lock check exit?
std::mutex m;
std::condition_variable cv;
int task = 0;
void worker_thread2()
{
{
// std::lock_guard<std::mutex> lk(m);
task++;
}
cv.notify_all();
LOG("notify_all");
}
int main()
{
std::thread worker(worker_thread2);
{
std::unique_lock<std::mutex> lk(m);
cv.wait_for(lk, std::chrono::milliseconds(5000), [&]{
if (task == 1) {
LOG("1111111");
return true;
} else {
LOG("0000000");
return false;
}
});
}
std::string m = "Back in main(), data = " + std::to_string(task);
LOG(m);
worker.join();
}
D:\code\c++11\condition_variable\cmake-build-debug\condition_variable.exe 2023-6-8 20:37:15.208 00000002023-6-8 20:37:15.208 notify_all
2023-6-8 20:37:20.210 1111111 2023-6-8 20:37:20.212 Back in main(), data = 1
Process finished with exit code 0