Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

predicate for condition variable

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?

like image 482
claudius Avatar asked Apr 03 '14 10:04

claudius


People also ask

What is conditional variable?

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.

What is condition variable C++?

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.

What does condition variable wait do?

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).

What is condition variable in multithreading?

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.


1 Answers

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);
}
like image 115
Wandering Logic Avatar answered Oct 08 '22 13:10

Wandering Logic