Search code examples
stlthread-synchronization

unlocking std::unique_lock without destroying it


If create a unique_lock as below, can I unlock it without destroying or getting out of scope? In other words is this safe/acceptable?

std::mutex queueMutex;

// My understanding is that this locks the mutex
std::unique_lock<std::mutex> lk(queueMutex); 
{
     // My critical section
}

//  Is it unlocking it properly, or do I have to pop it from the stack?
lk.unlock();

thx!


Solution

  • It is safe and acceptable, calling unlock() will unlock the mutex and make the unique_lock to forget about it so it does not unlock it again in the dtor.

    Having said that, scoping is preferable in most cases for readability because if the function/scope is long and unlock is inside an if or another conditional construct it might be hard for the reader to follow.