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
The mutex does not become unlocked until the owner has called pthread_mutex_unlock() for each successful lock request that it has outstanding on the mutex. An errorcheck mutex checks for deadlock conditions that occur when a thread relocks an already held mutex.
If the mutex is already locked, the calling thread shall block until the mutex becomes available. This operation shall return with the mutex object referenced by mutex in the locked state with the calling thread as its owner.
Mutexes are used to protect shared data structures being accessed concurrently. The thread that locks the mutex owns it, and the owning thread should be the only thread to unlock the mutex.
An RAII guard is returned to allow scoped unlock of the lock. When the guard goes out of scope, the mutex will be unlocked.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With