问题
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