PVData C++  8.0.6
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
lock.h
1 /* lock.h */
2 /*
3  * Copyright information and license terms for this software can be
4  * found in the file LICENSE that is included with the distribution
5  */
9 #ifndef LOCK_H
10 #define LOCK_H
11 
12 #include <stdexcept>
13 
14 #include <epicsMutex.h>
15 #include <shareLib.h>
16 
17 #include <pv/noDefaultMethods.h>
18 
19 
20 /* This is based on item 14 of
21  * Effective C++, Third Edition, Scott Meyers
22  */
23 
24 // TODO reference counting lock to allow recursions
25 
26 namespace epics { namespace pvData {
27 
28 typedef epicsMutex Mutex;
29 
36 class Lock {
37  EPICS_NOT_COPYABLE(Lock)
38 public:
43  explicit Lock(Mutex &m)
44  : mutexPtr(m), locked(true)
45  { mutexPtr.lock();}
50  ~Lock(){unlock();}
55  void lock()
56  {
57  if(!locked)
58  {
59  mutexPtr.lock();
60  locked = true;
61  }
62  }
66  void unlock()
67  {
68  if(locked)
69  {
70  mutexPtr.unlock();
71  locked=false;
72  }
73  }
78  bool tryLock()
79  {
80  if(locked) return true;
81  if(mutexPtr.tryLock()) {
82  locked = true;
83  return true;
84  }
85  return false;
86  }
91  bool ownsLock() const{return locked;}
92 private:
93  Mutex &mutexPtr;
94  bool locked;
95 };
96 
97 
98 }}
99 #endif /* LOCK_H */
Lock(Mutex &m)
Definition: lock.h:43
bool tryLock()
Definition: lock.h:78
A lock for multithreading.
Definition: lock.h:36
void lock()
Definition: lock.h:55
bool ownsLock() const
Definition: lock.h:91
void unlock()
Definition: lock.h:66