mutex v.s. unique_lock
The usage of std::mutex
and std::unique_lock
are similar. They both have lock()
and unlock()
operations. The difference is that 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.
std::mutex mtx;
mtx.lock();
... //protected stuff
mtx.unlock();
... //non-protected stuff
mtx.lock();
... //etc
std::mutex mtx;
std::unique_lock<std::mutex> lck(mtx);
... //protected stuff
lck.unlock();
... //non-protected stuff
lck.lock();
... //etc
unique_lock v.s. lock_guard
The difference between std::unique_lock
and std::lock_guard
is that you can lock and unlock a std::unique_lock
, while std::lock_guard
will be locked only once on construction and unlocked on destruction.
void foo() {
std::mutex mtx;
std::lock_guard<std::mutex> lg(mtx);
... //protected stuff
} //mutex is automatically released when lock goes out of scope