mutex.lock vs unique_lock

Morgan Fouque picture Morgan Fouque · Jun 21, 2016 · Viewed 16.3k times · Source

When should I prefer the first piece of code to the second, and do they have fundamental differences

std::mutex mtx;
mtx.lock();
... //protected stuff
mtx.unlock();
... //non-protected stuff
mtx.lock();
... //etc

and

std::mutex mtx;
std::unique_lock<std::mutex> lck(mtx);
... //protected stuff
lck.unlock();
... //non-protected stuff
lck.lock();
... //etc

I do understand that lock_guard is basically a unique_lock without the lock and unlock functions, but I'm having hard time differentiating a mutex and a lock using a mutex.

Answer

gbehar picture gbehar · Jun 21, 2016

Yes, the std::unique_lock calls unlock on the mutex in its destructor.

The benefit of this is that in case some exception is thrown, you are sure that the mutex will unlock when leaving the scope where the std::unique_lock is defined.