Fawkes API  Fawkes Development Version
fawkes::MutexLocker Class Reference

Mutex locking helper. More...

#include <>>

Public Member Functions

 MutexLocker (RefPtr< Mutex > mutex, bool initially_lock=true)
 Constructor. More...
 
 MutexLocker (Mutex *mutex, bool initially_lock=true)
 Constructor. More...
 
 ~MutexLocker ()
 Destructor. More...
 
void relock ()
 Lock this mutex, again. More...
 
void unlock ()
 Unlock the mutex. More...
 

Detailed Description

Mutex locking helper.

This class is a convenience function which can help you prevent a quite a few headaches. Consider the following code.

void my_function()
{
mutex->lock();
for (int i = 0; i < LIMIT; ++i) {
if ( failure ) {
mutex->unlock
}
}
switch ( someval ) {
VALA:
mutex->unlock();
return;
VALB:
do_something();
}
try {
do_function_that_throws_exceptions();
} catch (Exception &e) {
mutex->unlock();
throw;
}
mutex->unlock();
}

This is not a complete list of examples but as you see if you have many exit points in a function it becomes more and more work to have correct locking behavior.

This is a lot simpler with the MutexLocker. The MutexLocker locks the given mutex on creation, and unlocks it in the destructor. If you now have a mutex locker on the stack as integral type the destructor is called automagically on function exit and thus the mutex is appropriately unlocked. The code would look like this:

void my_function()
{
MutexLocker ml(mutex);
// do anything, no need to call mutex->lock()/unlock() if only has to be
// called on entering and exiting the function.
}
Author
Tim Niemueller

Definition at line 33 of file mutex_locker.h.

Constructor & Destructor Documentation

◆ MutexLocker() [1/2]

fawkes::MutexLocker::MutexLocker ( RefPtr< Mutex mutex,
bool  initially_lock = true 
)

Constructor.

Parameters
mutexMutex to lock/unlock appropriately.
initially_locktrue to lock the mutex in the constructor, false to not lock

Definition at line 90 of file mutex_locker.cpp.

◆ MutexLocker() [2/2]

fawkes::MutexLocker::MutexLocker ( Mutex mutex,
bool  initially_lock = true 
)

Constructor.

Parameters
mutexMutex to lock/unlock appropriately.
initially_locktrue to lock the mutex in the constructor, false to not lock

Definition at line 105 of file mutex_locker.cpp.

References fawkes::Mutex::lock().

◆ ~MutexLocker()

fawkes::MutexLocker::~MutexLocker ( )

Destructor.

Definition at line 116 of file mutex_locker.cpp.

References fawkes::Mutex::unlock().

Member Function Documentation

◆ relock()

void fawkes::MutexLocker::relock ( )

Lock this mutex, again.

Use this if you unlocked the mutex from the outside.

Definition at line 132 of file mutex_locker.cpp.

References fawkes::Mutex::lock().

Referenced by fawkes::LuaContext::restart().

◆ unlock()


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