I am new to multi threading. While writing multi threaded code in C++11 using condition variable , I use the following construct
while(predicate) {
cond_var.wait(&lock);
}
However, I have been reading Deitel's third edition book on operating systems(chp 6) where the following construct is being used
if(predicate) {
cond_var.wait(&lock);
}
So, what's the difference? Why isn't the book using while? Isn't spurious call an issue?
Condition variables are synchronization primitives that enable threads to wait until a particular condition occurs. Condition variables are user-mode objects that cannot be shared across processes. Condition variables enable threads to atomically release a lock and enter the sleeping state.
Condition variable. A condition variable is an object able to block the calling thread until notified to resume. It uses a unique_lock (over a mutex ) to lock the thread when one of its wait functions is called.
condition_variable::wait wait causes the current thread to block until the condition variable is notified or a spurious wakeup occurs, optionally looping until some predicate is satisfied (bool(stop_waiting()) == true).
Condition Variable is a kind of Event used for signaling between two or more threads. One or more thread can wait on it to get signaled, while an another thread can signal this.
Spurious wakeup is always a potential issue. For example, look at the answers here: Do spurious wakeups actually happen?. Perhaps Deitel's code is part of a larger loop that can help them deal with the spurious wakeup? Or maybe it's just a typo.
In any case, there's never a (good) reason not to use your construct, and in fact the wait
function has a variant that does it for you (http://en.cppreference.com/w/cpp/thread/condition_variable/wait).
template< class Predicate >
void wait( std::unique_lock<std::mutex>& lock, Predicate pred );
which is equivalent to:
while (!pred()) {
wait(lock);
}
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