Reusing unique_lock in a consumer loop

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(); // process m } } 

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?

+5
source share
1 answer

As stated in cppreference , the std::unique_lock is as follows:

 explicit unique_lock( mutex_type& m ); 

The constructor will do the following:

Creates a unique_lock with m as the associated mutex. Additionally blocks the associated mutex by calling m.lock () . The behavior is undefined if the current thread already owns the mutex, unless the mutex is recursive.

Thus, the code blocks the mutex at each iteration. Moving it out of a loop would change the logic.

+6
source

Source: https://habr.com/ru/post/1270391/


All Articles