Belle II Software development
GenericLockGuard< AMutex > Class Template Reference

Lock Guard for a Mutex instance. More...

#include <LockGuard.h>

Public Member Functions

 GenericLockGuard (AMutex &mutex)
 Construct a new LockGuard locking the mutex.
 
 ~GenericLockGuard ()
 Automatically release the lock on destruction.
 

Private Member Functions

 GenericLockGuard (const GenericLockGuard &)
 Do not allow to copy a lock guard.
 
GenericLockGuardoperator= (const GenericLockGuard &)
 Do not allow to copy a lock guard.
 

Private Attributes

AMutex & m_mutex
 The mutex hold by this lock guard.
 

Detailed Description

template<class AMutex>
class Belle2::GenericLockGuard< AMutex >

Lock Guard for a Mutex instance.

If a new instance of this class is generated, the mutex is locked. On destruction, it is automatically unlocked. This allows to write very simple functions with locks, e.g.

Mutex m;

LockGuard lock(m); try { throw std::exception(); // or return some_value; } catch(...) { std::cout << "Some exception" << std::endl; }

without the needs to think about unlocking it, as it is done automatically. It toughly follows the C++11 lock_guard and RIIA (https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization)

WARNING: the lock can not be unlocked on uncaught exceptions (because they terminate the program by definition). This is not a problem with the mutex, as it is released by the operation system on program termination.

The GenericLockGuard is a templated version of the lock guard. Use the specialised LockGuard of you want to lock a Mutex or the MLockGuard for an MMutex.

Definition at line 47 of file LockGuard.h.

Constructor & Destructor Documentation

◆ GenericLockGuard()

GenericLockGuard ( AMutex &  mutex)
inlineexplicit

Construct a new LockGuard locking the mutex.

Definition at line 50 of file LockGuard.h.

50 : m_mutex(mutex)
51 {
52 m_mutex.lock();
53 }
AMutex & m_mutex
The mutex hold by this lock guard.
Definition: LockGuard.h:69

◆ ~GenericLockGuard()

~GenericLockGuard ( )
inline

Automatically release the lock on destruction.

Definition at line 56 of file LockGuard.h.

57 {
58 m_mutex.unlock();
59 }

Member Data Documentation

◆ m_mutex

AMutex& m_mutex
private

The mutex hold by this lock guard.

Definition at line 69 of file LockGuard.h.


The documentation for this class was generated from the following file: