Unlock mutex on exception

馋奶兔 提交于 2020-05-29 01:03:58

问题


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

To guaranty the unlock i must call mutex.unlock() in catch block and in normal case. Is there any option to avoid duplication?

Thank You


回答1:


What you are looking for is a mutex wrapper like 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
}

When lock goes out of scope, its destructor unlocks the underlying mutex _mutex.

See also std::unique_lock, this class provides some more features and might add some more overhead. In this case astd::lock_guard is sufficient.



来源:https://stackoverflow.com/questions/36099580/unlock-mutex-on-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!