在异常时解锁互斥锁

tam*_*bel 5 c++ mutex exception

mutex.lock();
try
{
    foo(); // can throw exception
}
catch (...)
{
    mutex.unlock();
    throw;
}
mutex.unlock();
Run Code Online (Sandbox Code Playgroud)

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

谢谢

ser*_*gej 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
}
Run Code Online (Sandbox Code Playgroud)

lock超出范围时,其析构函数会解锁基础互斥锁_mutex.

另请参见 std::unique_lock,此类提供了一些更多功能,可能会增加一些开销.在这种情况下,a std::lock_guard就足够了.