首页 > 代码库 > C++11中lock_guard和unique_lock的区别

C++11中lock_guard和unique_lock的区别

c++11中有一个区域锁lock_guard,还有第二个区域锁unique_lock。

区域锁lock_guard使用起来比较简单,除了构造函数外没有其他member function,在整个区域都有效。

区域锁unique_guard除了lock_guard的功能外,提供了更多的member_function,相对来说更灵活一些。

 unique_guard的最有用的一组函数为:

lock
locks the associated mutex 
(public member function)
try_lock
tries to lock the associated mutex, returns if the mutex is not available 
(public member function)
try_lock_for
attempts to lock the associated TimedLockable mutex, returns if the mutex has been unavailable for the specified time duration 
(public member function)
try_lock_until
tries to lock the associated TimedLockable mutex, returns if the mutex has been unavailable until specified time point has been reached 
(public member function)
unlock
unlocks the associated mutex 

 

通过上面的函数,可以通过lock/unlock可以比较灵活的控制锁的范围,减小锁的粒度。

通过try_lock_for/try_lock_until则可以控制加锁的等待时间,此时这种锁为乐观锁。

C++11中lock_guard和unique_lock的区别