Boanerges
Boanerges

Reputation: 546

Is it right to use std::condition_variable::wait inside a while loop?

I am currently working on the std::condition_variable. Is it right to use std::condition_variable::wait() inside the while loop and not to rely on the std::condition_variable::notify() at all?

Should each std::condition_variable::wait() mandatorily have std::condition_variable::notify() ?

Upvotes: 2

Views: 1522

Answers (1)

Pete Becker
Pete Becker

Reputation: 76438

You use it in a loop, and you rely on notify().

The problem is that a condition variable is allowed to wake up "spuriously", that is, without being signaled. That makes it easier to implement, but it requires you to check that you're really where you think you are. So you write a loop:

std::unique_lock<std::mutex> lk(some_mutex);
while (condition_not_satisfied())
    cond_var.wait(lk);

Where some_mutex provides a critical area for the variable(s) used in the condition.

Or, as Slava points out, you can use the predicate version:

std::unique_lock<std::mutex> lk(some_mutex);
cond_var.wait(lk, some_callable_object_that_checks_the_predicate);

(I've never liked that form, so I tend to forget about it)

Upvotes: 6

Related Questions