I stumbled over the following code in Bjarne Stroustrup's "The C++ Programming Language, 4th Edition" on page 119:
queue<Message> mqueue;
condition_variable mcond;
mutex mmutex;
void consumer()
{
while(true) {
unique_lock<mutex> lck{mmutex};
mcond.wait(lck);
auto m = mqueue.front();
mqueue.pop();
lck.unlock();
// process m
}
}
There is also a producer thread which pushes Message
to the queue and notifies the waiting thread in a loop.
My question is: Is it required to create a new unique_lock
in every iteration of the loop? It seems unneccesary to me, because in the next line, mcond.wait(lck)
, the lock gets unlocked directly after locking it in the line before.
From a performance point of view, couldn't the lck
variable just be initialized before the loop starts?
lck
out of the loop would not really make much difference here. The lock would be locked outside the loop, then immediately inside the loop be unlocked by the very samewait
call. – Dewclawm
is processed, the loop starts again. However this time, the mutex does not get locked again before the wait call. Am I right with this one? – Compilationwait
function expects the lock to be locked! If it's not locked then you have undefined behavior. So the placement is not only about "closeness", but about avoiding problems. – Dewclawwait
expects the lock to be locked then of course it has to be done this way. – Compilationunique_lock
. (You're basically worrying about whether driving barefoot might improve your gas mileage.) – Zimmerman