why does the wait() method of a boost::conditiona_variable require a boost::unique_lock object as parameter and not a simple boost::mutex?
Actually, it is not completely clear the purpose of a unique_lock at all. Why should I create another wrapper object around my boost::mutex, and what is the impact on performance?
For example, assume I have two threads, thread1 and thread2:
on thread1
void process() {
while(true){
while (objectToProcess == NULL) {
boost::unique_lock lock(mutex);
waitingVariable.wait(lock);
}
doSomething(objToProcess);
objToProcess = NULL;
waitingVariable.notify();
}
}
on thread2:
void feedProcessor() {
while(true) {
while (objectToProcess != NULL) {
boost::unique_lock lock(mutex);
waitingVariable.wait(lock);
}
objToProcess = createNewObjectToProcess();
waitingVariable.notify();
}
}
In this case, I find wasteful to create new unique_lock objects every time I need to call the wait() method of a conditional variable. Can you please enlighten me on the purpose of such objects and whether they introduce significant overhead?
Thanks!
(I see that my question overlaps with this question, but my concern is more about overhead than purpose...)
The idea of a condition variable is the following:
You protect the consumption of an asynchronous event via an unique_lock. But you only lock the mutex if the condition variable has at least one not yet consumed event available. Otherwise the lock is not locked and waits instead for a notify event.
With this understanding your code should change to the following, in order to protect your processing of the object:
see http://www.boost.org/doc/libs/1_55_0/doc/html/thread/synchronization.html#thread.synchronization.condvar_ref