首页 > 代码库 > 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的区别
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。