Std :: condition_variable :: wait with predicate

The documentation for std :: condition_variable has an overload of wait () that takes a predicate function as an argument. The function will wait until the first wake_up, at which the predicate function will be true.

In the documentation

It is argued that this is equivalent to:

while (!pred()) {
    wait(lock);
}

But also:

This overload can be used to ignore false awakenings, waiting for a certain condition to become true. Please note that before entering this method, the lock must be obtained, after it leaves (lock), it will also be restored, i.e. The lock can be used as security for pred () access.

I'm not sure I understand if they are strictly equivalent (in this case, I prefer a simple while loop that is easier to read than overloading with lambda in my case), or is this overloading (possibly depending on implementation) more efficient?

Can an implementation evaluate a predicate in a notification thread before waking up a waiting thread to avoid waking up when the test condition is false? C ++ guru thread is needed here ...

thanks

+4
source share
2 answers

, , , . , , , . , gcc 4.9.2 :

template<typename _Predicate>
  void
  wait(unique_lock<mutex>& __lock, _Predicate __p)
  {
      while (!__p())
        wait(__lock);
  }

, , , - . , , . , , . , , , , , - . :

cond_var.wait(lock, []() { return bool_var == true; })
+2

, ( while wait + predicate) . while, . predicate() wait().

: wait, , , predicate() , , ( ).

, , , boolean, while, . , predicate ? while lambda? , , ? , lambdas , .

0

Source: https://habr.com/ru/post/1615757/


All Articles