|
PVData C++
|
00001 /* lock.h */ 00002 /* 00003 * Copyright information and license terms for this software can be 00004 * found in the file LICENSE that is included with the distribution 00005 */ 00009 #ifndef LOCK_H 00010 #define LOCK_H 00011 00012 #include <stdexcept> 00013 00014 #include <epicsMutex.h> 00015 #include <shareLib.h> 00016 00017 #include <pv/noDefaultMethods.h> 00018 00019 00020 /* This is based on item 14 of 00021 * Effective C++, Third Edition, Scott Meyers 00022 */ 00023 00024 // TODO reference counting lock to allow recursions 00025 00026 namespace epics { namespace pvData { 00027 00028 typedef epicsMutex Mutex; 00029 00036 class Lock { 00037 EPICS_NOT_COPYABLE(Lock) 00038 public: 00043 explicit Lock(Mutex &m) 00044 : mutexPtr(m), locked(true) 00045 { mutexPtr.lock();} 00050 ~Lock(){unlock();} 00055 void lock() 00056 { 00057 if(!locked) 00058 { 00059 mutexPtr.lock(); 00060 locked = true; 00061 } 00062 } 00066 void unlock() 00067 { 00068 if(locked) 00069 { 00070 mutexPtr.unlock(); 00071 locked=false; 00072 } 00073 } 00078 bool tryLock() 00079 { 00080 if(locked) return true; 00081 if(mutexPtr.tryLock()) { 00082 locked = true; 00083 return true; 00084 } 00085 return false; 00086 } 00091 bool ownsLock() const{return locked;} 00092 private: 00093 Mutex &mutexPtr; 00094 bool locked; 00095 }; 00096 00097 00098 }} 00099 #endif /* LOCK_H */
1.7.4