Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 572
Vasily Avatar asked Feb 25 '13 17:02

Vasily


2 Answers

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();
like image 173
Mike Seymour Avatar answered Nov 14 '22 00:11

Mike Seymour


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.

like image 36
Slava Avatar answered Nov 14 '22 00:11

Slava