在异常时解锁互斥锁

时间:2016-03-19 08:30:30

标签: c++ exception mutex

mutex.lock();
try
{
    foo(); // can throw exception
}
catch (...)
{
    mutex.unlock();
    throw;
}
mutex.unlock();

为了保证解锁,我必须在catch块中调用mutex.unlock(),正常情况下。有没有选择避免重复?

谢谢

1 个答案:

答案 0 :(得分:8)

您正在寻找的是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就足够了。

相关问题