Reputation: 568
I know that sometime, thread in condition-variable wait can be wake - up from Windows, which send them a notify without reason. So we overload the function wait with a function which verify if the thread must be wake up or not.
Suppose to have this pseudo:
if (A == false)
conditionVariable.wait (lock, []() { return (A == true) });
cout << "Exit from wait " << endl;
Suppose that immediately before the wait, another thread put A = true, and it does a conditionVariable.notifyAll() (but I cannot listen it because I'm not on wait yet). After that, I enter in the wait and nobody could take the lock in other part of the code. The behaviour of my program is the execution of the cout! I'd like to understand if the motivation is:
A) Even if nobody notify the thread, it exit from the wait because the lock is free and because the condition A==true is true.
B) The synchronization is wrong, teorically your program should be wait forever but a "Windows notify" save you even if you miss the notification.
Thanks for your help.
Upvotes: 1
Views: 472
Reputation: 4283
Note that the reference mentions that wait-with-predicate is equivalent to:
while (!pred()) {
wait(lock);
}
Your if
is unnecessary. As to your question: behaviour is still B) (broken) for the reasons you list yourself. Note that even the reference has this snippet before notifying the waiting thread:
// send data to the worker thread
{
std::lock_guard<std::mutex> lk(m);
ready = true;
std::cout << "main() signals data ready for processing\n";
}
cv.notify_one();
Acquiring the lock first before setting ready
ensures the worker sees the expected sequence.
Upvotes: 1