PVData C++  8.0.2
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  */
6 /**
7  * @author mrk
8  */
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 
30 /**
31  * @brief A lock for multithreading
32  *
33  * This is based on item 14 of
34  * * Effective C++, Third Edition, Scott Meyers
35  */
36 class Lock {
38 public:
39  /**
40  * Constructor
41  * @param m The mutex for the facility being locked.
42  */
43  explicit Lock(Mutex &m)
44  : mutexPtr(m), locked(true)
45  { mutexPtr.lock();}
46  /**
47  * Destructor
48  * Note that destructor does an automatic unlock.
49  */
51  /**
52  * Take the lock
53  * Recursive locks are supported but each lock must be matched with an unlock.
54  */
55  void lock()
56  {
57  if(!locked)
58  {
59  mutexPtr.lock();
60  locked = true;
61  }
62  }
63  /**
64  * release the lock.
65  */
66  void unlock()
67  {
68  if(locked)
69  {
70  mutexPtr.unlock();
71  locked=false;
72  }
73  }
74  /**
75  * If lock is not held take the lock.
76  * @return (false,true) if caller (does not have, has) the lock.
77  */
78  bool tryLock()
79  {
80  if(locked) return true;
81  if(mutexPtr.tryLock()) {
82  locked = true;
83  return true;
84  }
85  return false;
86  }
87  /**
88  * See if caller has the lock,
89  * @return (false,true) if caller (does not have, has) the lock.
90  */
91  bool ownsLock() const{return locked;}
92 private:
93  Mutex &mutexPtr;
94  bool locked;
95 };
96 
97 
98 }}
99 #endif /* LOCK_H */
bool ownsLock() const
Definition: lock.h:91
Lock(Mutex &m)
Definition: lock.h:43
bool tryLock()
Definition: lock.h:78
A lock for multithreading.
Definition: lock.h:36
virtual void serialize(ByteBuffer *buffer, SerializableControl *flusher, std::size_t offset, std::size_t count) const =0
void lock()
Definition: lock.h:55
#define EPICS_NOT_COPYABLE(CLASS)
Disable implicit copyable.
void unlock()
Definition: lock.h:66