1. 程式人生 > >C++11中lock_guard和unique_lock的區別

C++11中lock_guard和unique_lock的區別

target san color member uri display each for clas

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的區別