Fawkes API
Fawkes Development Version
|
#include <>>
Public Member Functions | |
MutexLocker (RefPtr< Mutex > mutex, bool initially_lock=true) | |
Constructor. | |
MutexLocker (Mutex *mutex, bool initially_lock=true) | |
Constructor. | |
~MutexLocker () | |
Destructor. | |
void | relock () |
Lock this mutex, again. | |
void | unlock () |
Unlock the mutex. |
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. }
Constructor.
mutex | Mutex to lock/unlock appropriately. |
initially_lock | true to lock the mutex in the constructor, false to not lock |
Definition at line 90 of file mutex_locker.cpp.
fawkes::MutexLocker::MutexLocker | ( | Mutex * | mutex, |
bool | initially_lock = true |
||
) |
Constructor.
mutex | Mutex to lock/unlock appropriately. |
initially_lock | true to lock the mutex in the constructor, false to not lock |
Definition at line 105 of file mutex_locker.cpp.
References fawkes::Mutex::lock().
fawkes::MutexLocker::~MutexLocker | ( | ) |
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().
void fawkes::MutexLocker::unlock | ( | ) |
Unlock the mutex.
Definition at line 145 of file mutex_locker.cpp.
References fawkes::Mutex::unlock().
Referenced by fawkes::ThreadManager::try_recover(), and fawkes::FawkesNetworkClientRecvThread::recv().