mutex, unique_lock & lock_guard

本文对比了std::mutex与std::unique_lock的使用,强调std::unique_lock在析构时自动解锁mutex,确保异常安全。同时,介绍了std::unique_lock与std::lock_guard的区别,前者可在运行时决定是否锁定,后者在构造时锁定并在析构时释放。

mutex v.s. unique_lock

The usage of std::mutex and std::unique_lock are similar. They both have lock() and unlock() operations. The difference is that std::unique_lock calls unlock on the mutex in its destructor. The benefit of this is that in case some exception is thrown, you are sure that the mutex will unlock when leaving the scope where the std::unique_lock is defined.

std::mutex mtx;
mtx.lock();
... //protected stuff
mtx.unlock();
... //non-protected stuff
mtx.lock();
... //etc
std::mutex mtx;
std::unique_lock<std::mutex> lck(mtx);
... //protected stuff
lck.unlock();
... //non-protected stuff
lck.lock();
... //etc

unique_lock v.s. lock_guard

The difference between std::unique_lock and std::lock_guard is that you can lock and unlock a std::unique_lock, while std::lock_guard will be locked only once on construction and unlocked on destruction.

void foo() {
	std::mutex mtx;
	std::lock_guard<std::mutex> lg(mtx);
	... //protected stuff
} //mutex is automatically released when lock goes out of scope 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值