I am going through condition variable article at following location
Here we have following code as example
#include "tbb/compat/condition_variable"
using namespace std;
condition_variable my_condition;
tbb::mutex my_mtx;
bool present = false;
void producer() {
unique_lock<tbb::mutex> ul( my_mtx );
present = true;
my_condition.notify_one();
}
void consumer() {
while( !present ) {
unique_lock<tbb::mutex> ul( my_mtx );
my_condition.wait( ul );
}
}
My understanding is that we use condition variable to wait on an event. I have following questions
- Why are we using mutex here while we are using condition
variable? - In consumer() function in while loop we are taking mutex and
waiting on condition, how can producer function can lock mutex
if consumer already taken it and how can it notify it doesn’t it a deadlock? - How unique_lock is different from scoped_lock?
Thanks for your help in clarfiying my questions.
The basics of the condition variable require a lock to work correctly.
Only the thread with the lock should be trying to change the state of the condition variable (ie by calling one of the condition variable functions (it is also to protect the object you are really working on)).
When you call wait() on the condition variable the thread is put to sleep and the mutex is released. When a thread is woken up it must re-acquire the lock before the function wait() returns to the user code.
It does not deadlock because wait() is releasing the lock before putting the thread to sleep.
In this context none. But if you have any specific implementation of these then please specify the implementation and we can discuss it in more detail.