Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing a unique_lock in a consumer loop

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?

like image 638
Bobface Avatar asked Jul 31 '17 12:07

Bobface


1 Answers

As stated on cppreference, the std::unique_lock constructor is as such:

explicit unique_lock( mutex_type& m );

The constructor will do the following:

Constructs a unique_lock with m as the associated mutex. Additionally locks the associated mutex by calling m.lock(). The behavior is undefined if the current thread already owns the mutex except when the mutex is recursive.

So the code locks the mutex on every iteration. Moving it out of the loop would change the logic.

like image 80
Vasiliy Galkin Avatar answered Sep 28 '22 08:09

Vasiliy Galkin