Vasily
Vasily

Reputation: 255

std::condition_variable spurious blocking

As you know, condition variables should be called in cycle to avoid spurious wake-ups. Like this:

while (not condition)
    condvar.wait();

If another thread wants to wake up waiting thread, it must set condition flag to true. E.g.:

condition = true;
condvar.notify_one();

I wonder, is it possible for condition variable to be blocked by this scenario:

1)Waiting thread checks condition flag, and finds it is equal to FALSE, so, it's going to enter condvar.wait() routine.

2)But just before this (but after condition flag checking) waiting thread is preempted by kernel (e.g. because of time slot expiration).

3) At this time, another thread wants to notify waiting thread about condition. It sets condition flag to TRUE and calls condvar.notify_one();

4) When kernel scheduler runs first thread again, it enters condvar.wait() routine, but the notification have been already missed.

So, waiting thread can't exit from condvar.wait(), despite condition flag is set to TRUE, because there is no wake up notifications anymore.

Is it possible?

Upvotes: 6

Views: 7131

Answers (3)

Maor Dahan
Maor Dahan

Reputation: 392

Mike Seymour his answer is incomplete because there is a race condition which ends up with wakeup lost. The right way is to (now with the c++11) is as follow:

Thread1:

std::unique_lock<std::mutex> lck(myMutex);
condvar.wait(lck, []{ return condition; }); // prevent spurious wakeup
// Process data

Thread2:

{
    std::lock_guard<std::mutex> lck(myMutex);
    condition = true;
} // unlock here! prevent wakeup lost
condvar.notify_one();

Upvotes: 2

Mike Seymour
Mike Seymour

Reputation: 254631

That is exactly why a condition variable must be used in conjunction with a mutex, in order to atomically update the state and signal the change. The full code would look more like:

unique_lock<mutex> lock(mutex);
while (not condition)
    condvar.wait(lock);

and for the other thread:

lock_guard<mutex> lock(mutex);
condition = true;
condvar.notify_one();

Upvotes: 16

Slava
Slava

Reputation: 44268

You example missing small part, but that explains why that is not possible if done correctly:

while (not condition) // when you check condition mutex is locked
    condvar.wait( mutex ); // when you wait mutex is unlocked

So if you change condition to true under the same mutex lock, this situation will not happen.

Upvotes: 4

Related Questions