Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unlock mutex on exception

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

like image 487
tambel Avatar asked Mar 19 '16 08:03

tambel


People also ask

How do you unlock a mutex?

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.

What happens if a mutex is not unlocked?

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.

Can any thread unlock a mutex?

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.

How do you unlock mutex in Rust?

An RAII guard is returned to allow scoped unlock of the lock. When the guard goes out of scope, the mutex will be unlocked.


1 Answers

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.

like image 182
sergej Avatar answered Oct 01 '22 20:10

sergej