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](http://en.cppreference.com/w/cpp/thread/unique_lock/lock) locks the associated mutex

(public member function)
[try_lock](http://en.cppreference.com/w/cpp/thread/unique_lock/try_lock) tries to lock the associated mutex, returns if the mutex is not available

(public member function)
[try_lock_for](http://en.cppreference.com/w/cpp/thread/unique_lock/try_lock_for) attempts to lock the associated [`TimedLockable`](http://en.cppreference.com/w/cpp/concept/TimedLockable) mutex, returns if the mutex has been unavailable for the specified time duration

(public member function)
[try_lock_until](http://en.cppreference.com/w/cpp/thread/unique_lock/try_lock_until) tries to lock the associated [`TimedLockable`](http://en.cppreference.com/w/cpp/concept/TimedLockable) mutex, returns if the mutex has been unavailable until specified time point has been reached

(public member function)
[unlock](http://en.cppreference.com/w/cpp/thread/unique_lock/unlock) unlocks the associated mutex

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

通过try_lock_for/try_lock_until则可以控制加锁的等待时间,此时这种锁为乐观锁。
原文链接: https://www.cnblogs.com/jiu0821/p/7269777.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/257697

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月14日 上午11:10
下一篇 2023年2月14日 上午11:10

相关推荐