异常时解锁互斥锁
Unlock mutex on exception
mutex.lock();
try
{
foo(); // can throw exception
}
catch (...)
{
mutex.unlock();
throw;
}
mutex.unlock();
为了保证解锁,我必须在捕获块和正常情况下调用mutex.unlock()
。有什么办法可以避免重复吗?
谢谢
您正在寻找的是一个互斥包装器,如下所示std::lock_guard
:
#include <mutex>
std::mutex _mutex;
void call_foo()
{
std::lock_guard<std::mutex> lock(_mutex);
try
{
foo(); // can throw exception
}
catch (...)
{
// the mutex is unlocked here...
throw;
}
// ... and here
}
当lock
超出范围时,其析构函数会解锁底层互斥锁_mutex
。
另请参阅std::unique_lock
,此类提供了更多功能,并可能增加一些开销。在这种情况下,std::lock_guard
就足够了。
相关文章:
- 我应该在锁定TBitmap画布后解锁它吗
- 虚假唤醒是否会解锁所有等待线程,甚至是不相关的线程?
- c++ 为什么我不应该从不同的线程解锁互斥锁
- 在新作用域中使用unique_lock是否等效于在使用共享资源的工作结束时解锁调用
- "data race"(不是真的)在通知条件变量并解锁关联的互斥锁后
- 程序输入密码并解锁窗口7,8,10
- 在通知之前完成手动解锁
- STD :: Mutex如何在不同的线程中解锁
- 如何使用单个解锁方法(可称为读取器或写入器)实现C++读写器锁?
- 如何在C 中自动汇总日志消息并自动解锁互斥X
- 如果我们已经手动解锁了unique_lock,那么破坏时会解锁吗?
- 正在解锁手动未定义/不良设计的锁定guard
- 从C 运行代码后解锁绑定(在R中)的问题
- 在功能返回之前,可以解锁Mutex会增加并发
- 当互斥锁解锁时,它会notify_all或notify_one
- 如何确保在C ++中解锁储物柜?哪种解决方案更好
- 我应该如何在一个功能中锁定wxMutex,并在另一个功能中将其解锁
- mutex::lock() 检查一次解锁状态是否已经被另一个线程锁定?
- 异常时解锁互斥锁
- 互斥锁解锁异常失败