gorbos
gorbos

Reputation: 9

condition_variable wait parameter?

What is this:

bool ready;
boost::mutex mutex;
boost::condition_variable cond;
boost::unique_lock<boost::mutex> lock(mutex);
cond.wait(lock,[]{return ready;});

The second parameter looks unfamiliar for me. Can somewone give me a hint?

regards Göran

Upvotes: 1

Views: 621

Answers (1)

sehe
sehe

Reputation: 393653

In addition to the other answerers, I'd add that it obviously has a lot to do with condition_variables.

Specificly, avoiding spurious wake-ups

What the condition-predicate accomplishes is that it will guarantee to

  • only return when the condition predicate is actually satisfied
  • not block on the condition variable if the condition is already met before the wait.

Doing that, it ensures that the lock is held at the appropriate times. You could write this manually, but it would be tedious and error-prone.

In fact, in many many cases people just forget about racy waits (waiting on a cv when the condition was already met) and spurious wake-ups.

Upvotes: 2

Related Questions