lundi 31 juillet 2017

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?

Aucun commentaire:

Enregistrer un commentaire