I came across the following code in Bjarne Stroustrup "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();
There is also a producer thread that pushes Message into the queue and notifies the waiting thread in the loop.
My question is: is it necessary to create a new unique_lock on each iteration of the loop? It seems unnecessary to me, because in the next line mcond.wait(lck) lock is unlocked immediately after it is locked in the line earlier.
In terms of performance, was it possible to initialize the lck variable before the start of the loop?
source share