C++ STL之unique_lock与lock_guard


std::lock_guard
 

lock_guard - C++ Reference

用于托管一个mutex 变量,负责对齐加锁解锁。

A lock guard is an object that manages a mutex object by keeping it always locked.

On construction, the mutex object is locked by the calling thread, and on destruction, the mutex is unlocked. It is the simplest lock, and is specially useful as an object with automatic duration that lasts until the end of its context. In this way, it guarantees the mutex object is properly unlocked in case an exception is thrown.

Note though that the lock_guard object does not manage the lifetime of the mutex object in any way: the duration of the mutex object shall extend at least until the destruction of the lock_guard that locks it.

MyNote:

@ 有变量std::mutex myMutex; 需要用其保护一段critical section, 则需要在前后使用myMutex.lock(), myMutex.unlock()函数。缺点是lock和unlock需要成对出现,如果critical section出现异常,则后面的unlock不会执行了,容易导致死锁。使用std::lock_gard<mutex>  myLockGuard(myMutex) , (lock_guard的构造函数将myMutex上锁), 可以以并解决这些个缺点。

@ lock_guard object does not manage the lifetime of the mutex object in any way。 lock_guard的析构函数调用时,会unLock其托管的mutex变量,如果这时该变量已经消失了那就没有意义了。故,lock_guard保存的是其托管的mutex对象的引用/地址吧。


std::unique_lock

unique_lock - C++ Reference

A unique lock is an object that manages a m

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

First Snowflakes

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值