异常时解锁互斥锁

Unlock mutex on exception

本文关键字:解锁 异常      更新时间:2023-10-16
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就足够了。