Reputation: 11661
I was reading this article on mutexes. and it states
The biggest difference between lock_guard and unique_lock is that lock_guard always owns the lock mode of the referenced mutex and unique_lock doesn't. Indeed, unique_lock may not even reference a mutex.
so far I only understand is that when we need to construct a lock but not lock the mutex we could use the std::unique_lock
. It is an improved version of std::lock_guard
Apart from that I do not see much difference. I would appreciate if someone could explain what does owning lock mode of a referenced mutex mean ?
Upvotes: 1
Views: 906
Reputation: 55897
When you use std::unique_lock
you can specify option in constructor.
http://en.cppreference.com/w/cpp/thread/unique_lock/unique_lock
There is three options std::defer_lock_t
, std::try_lock_t
and std::adopt_lock_t
.
std::defer_lock_t
Does not lock the associated mutex.
std::try_lock_t
Tries to lock the associated mutex without blocking by calling m.try_lock()
. The behavior is undefined if the current thread already owns the mutex except when the mutex is recursive.
std::adopt_lock_t
Assumes the calling thread already owns m.
When no option is specified (i.e. constructor called only with mutex param) - mutex is simply locked with mutex.lock()
function.
When you use std::lock_guard
you can only specify one option (std::adopt_lock_t
), in other case mutex will be locked with lock
function.
In all this cases in destructor of lock_guard
/unique_lock
mutex will be unlocked with call to mutex.unlock()
function, if mutex
is locked.
Upvotes: 1