If std::condition_variable
can be signaled due to the spurious wakeups (and we can't be sure that the condition we need is really satisfied), why do C++ Standard Library provide the overloads of wait()
method without a predicate? What are the scenarios when such behaviour can be used?
std::condition_variable The condition_variable class is a synchronization primitive that can be used to block a thread, or multiple threads at the same time, until another thread both modifies a shared variable (the condition), and notifies the condition_variable .
September 2020) A spurious wakeup happens when a thread wakes up from waiting on a condition variable that's been signaled, only to discover that the condition it was waiting for isn't satisfied. It's called spurious because the thread has seemingly been awakened for no reason.
condition_variable::wait wait causes the current thread to block until the condition variable is notified or a spurious wakeup occurs, optionally looping until some predicate is satisfied (bool(stop_waiting()) == true).
Condition variables allow us to synchronize threads via notifications. So, you can implement workflows like sender/receiver or producer/consumer. In such a workflow, the receiver is waiting for the sender's notification. If the receiver gets the notification, it continues its work.
Assume a complex condition: A || B
. When any part of the condition is true, appropriate action, actionA
or actionB
, should be perfomed.
Using predicate version, the code could be following:
cond.wait(lock, []{return (A || B);});
if(A) {
actionA();
}
else {
actionB();
}
But the code may be faster if use non-predicate wait:
while(true)
{
if(A) {
actionA();
break;
}
else if(B) {
actionB();
break;
}
cond.wait(lock);
}
Note, that unlike to the first variant, now every condition part is evaluated once.
There are more complex cases, when a condition cannot be written in a single expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With