C++11中lock_guard和unique_lock的區別


c++11中有一個區域鎖lock_guard,還有第二個區域鎖unique_lock。

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

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

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

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則可以控制加鎖的等待時間,此時這種鎖為樂觀鎖。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM