1. 程式人生 > >c++11的mutex unique_lock和lock_guard區別

c++11的mutex unique_lock和lock_guard區別

    區域鎖lock_guard使用起來比較簡單,除了建構函式外沒有其他member function,在整個區域都有效。

    區域鎖unique_guard除了lock_guard的功能外,提供了更多的member_function,相對來說更靈活一些。

    unique_guard的最有用的一組函式為:

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

    通過上面的函式,可以通過lock/unlock可以比較靈活的控制鎖的範圍,減小鎖的粒度。

    通過try_lock_for/try_lock_until則可以控制加鎖的等待時間,此時這種鎖為樂觀鎖。

    以上為粗淺理解,後面有新的心得在補充之。