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?
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With