1/*! 2\file Autolock.h 3\brief Implements a handy locking utility. 4*/ 5 6/*! 7\class BAutolock 8\ingroup support 9\ingroup libbe 10\brief Convenient utility to make parts of your code thread-safe easily. 11 12The autolocker uses a BLooper or a BLocker in order to protect a part 13of your code. This class is usually used in combination with a BLocker 14that protects a certain part of your code and data that are being 15accessed by multiple threads. While BAutolock does not add any features 16to locking, it provides a mechanism to easily lock and protect a part of your 17code. 18 19Normally, when you need to protect data, you would have to make sure that 20all your locks are paired with unlocks. Below is a simple example, but you 21can imagine that there are more complex situations where you might spend a 22lot of time debugging a hang because you didn't pair all the Lock()s with an 23Unlock(). See the example: 24 25\code 26status_t 27Receiver::HandleCall(Call *call) 28{ 29 ... work on call data ... 30 31 fDataLocker->Lock() 32 33 ... perform changes ... 34 35 if (!success) 36 { 37 fDataLocker->Unlock(); 38 return B_ERROR; 39 } 40 41 fDataLocker->Unlock() 42 return B_OK; 43} 44\endcode 45 46With the BAutolock this example can be rewritten as follows: 47\code 48status_t 49Receiver::HandleCall(Call *call) 50{ 51 ... work on call data ... 52 53 BAutolock autolock(fDataLocker); 54 55 ... perform changes ... 56 57 if (!success) 58 return B_ERROR; 59 60 return B_OK; 61} 62\endcode 63 64Since the object is created on stack, it is destroyed as soon as we leave 65the function. Because the destruction of the object causes it to unlock 66the BLocker or BLooper, you don't have to manually make sure that every 67exit from the function is properly unlocked. 68*/ 69 70/*! 71\fn BAutolock::BAutolock(BLooper *looper) 72\brief Create an object and lock the BLooper 73*/ 74 75/*! 76\fn BAutolock::BAutolock(BLocker *locker) 77\brief Create an object and lock the BLocker 78*/ 79 80/*! 81\fn BAutolock::BAutolock(BLocker &locker) 82\brief Create an object and lock the BLocker 83*/ 84 85/*! 86\fn BAutolock::~BAutolock() 87\brief Destroy the object and unlock the associated BLocker or BLooper 88*/ 89 90/*! 91\fn bool BAutolock::IsLocked(void) 92\brief Verify whether the associated BLocker or BLooper are actually locked. 93 94Basically you may assume that when the object is created, you are 95almost always sure the actual locking succeeds. It might fail if the 96BLocker or BLooper are destroyed though. The semaphore will be 97released and the Lock() call will fail. 98 99If you expect this to happen, you can use this method to help you 100protect yourself from any harm. 101\retval true The lock was acquired. 102\retval false Failed to acquire the lock. 103*/ 104