1 /* 2 * Copyright 2001-2009, Haiku, Inc. All Rights Reserved. 3 * Distributed under the terms of the MIT License. 4 */ 5 #ifndef _SUPPORT_AUTOLOCK_H 6 #define _SUPPORT_AUTOLOCK_H 7 8 9 #include <Locker.h> 10 #include <Looper.h> 11 12 13 class BAutolock { 14 public: 15 inline BAutolock(BLooper* looper); 16 inline BAutolock(BLocker* locker); 17 inline BAutolock(BLocker& locker); 18 inline ~BAutolock(); 19 20 inline bool IsLocked(); 21 22 inline bool Lock(); 23 inline void Unlock(); 24 25 private: 26 BLocker* fLocker; 27 BLooper* fLooper; 28 bool fIsLocked; 29 }; 30 31 32 inline 33 BAutolock::BAutolock(BLooper *looper) 34 : 35 fLocker(NULL), 36 fLooper(looper), 37 fIsLocked(looper->Lock()) 38 { 39 } 40 41 42 inline 43 BAutolock::BAutolock(BLocker *locker) 44 : 45 fLocker(locker), 46 fLooper(NULL), 47 fIsLocked(locker->Lock()) 48 { 49 } 50 51 52 inline 53 BAutolock::BAutolock(BLocker &locker) 54 : 55 fLocker(&locker), 56 fLooper(NULL), 57 fIsLocked(locker.Lock()) 58 { 59 } 60 61 62 inline 63 BAutolock::~BAutolock() 64 { 65 Unlock(); 66 } 67 68 69 inline bool 70 BAutolock::IsLocked() 71 { 72 return fIsLocked; 73 } 74 75 76 inline bool 77 BAutolock::Lock() 78 { 79 if (fIsLocked) 80 return true; 81 82 if (fLooper != NULL) 83 fIsLocked = fLooper->Lock(); 84 else 85 fIsLocked = fLocker->Lock(); 86 87 return fIsLocked; 88 } 89 90 91 inline void 92 BAutolock::Unlock() 93 { 94 if (!fIsLocked) 95 return; 96 97 fIsLocked = false; 98 if (fLooper != NULL) 99 fLooper->Unlock(); 100 else 101 fLocker->Unlock(); 102 } 103 104 #endif // _SUPPORT_AUTOLOCK_H 105