Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When can std::condition_variable be used without a predicate?

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?

like image 423
undermind Avatar asked Jan 26 '16 11:01

undermind


People also ask

What is std :: Condition_variable?

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 .

What is spurious wakeup C++?

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.

What does condition variable wait do?

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).

How does condition variable works C++?

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.


1 Answers

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.

like image 156
Tsyvarev Avatar answered Oct 07 '22 11:10

Tsyvarev