7
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

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55
tambel
  • 166
  • 1
  • 8

1 Answers1

11

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.

caligari
  • 2,110
  • 20
  • 25
sergej
  • 17,147
  • 6
  • 52
  • 89