libcopp  1.2.0
lock_holder.h
Go to the documentation of this file.
1 
15 #ifndef UTIL_LOCK_LOCK_HOLDER_H
16 #define UTIL_LOCK_LOCK_HOLDER_H
17 
18 #pragma once
19 
20 #include <cstring>
21 
23 
24 namespace util {
25  namespace lock {
26  namespace detail {
27  template <typename TLock>
29  bool operator()(TLock &lock) const {
30  lock.lock();
31  return true;
32  }
33  };
34 
35  template <typename TLock>
37  bool operator()(TLock &lock) const { return lock.try_lock(); }
38  };
39 
40  template <typename TLock>
42  void operator()(TLock &lock) const { lock.unlock(); }
43  };
44 
45  template <typename TLock>
47  bool operator()(TLock &lock) const { return lock.try_unlock(); }
48  };
49 
50  template <typename TLock>
52  bool operator()(TLock &lock) const {
53  lock.read_lock();
54  return true;
55  }
56  };
57 
58  template <typename TLock>
60  void operator()(TLock &lock) const { lock.read_unlock(); }
61  };
62 
63  template <typename TLock>
65  bool operator()(TLock &lock) const {
66  lock.write_lock();
67  return true;
68  }
69  };
70 
71  template <typename TLock>
73  void operator()(TLock &lock) const { lock.write_unlock(); }
74  };
75  } // namespace detail
76 
77  template <typename TLock, typename TLockAct = detail::default_lock_action<TLock>,
78  typename TUnlockAct = detail::default_unlock_action<TLock> >
79  class lock_holder {
80  public:
81  typedef TLock value_type;
82 
83  lock_holder(TLock &lock) : lock_flag_(&lock) {
84  if (false == TLockAct()(lock)) {
85  lock_flag_ = NULL;
86  }
87  }
88 
90  if (NULL != lock_flag_) {
91  TUnlockAct()(*lock_flag_);
92  }
93  }
94 
95  bool is_available() const { return NULL != lock_flag_; }
96 
97  private:
98  lock_holder(const lock_holder &) UTIL_CONFIG_DELETED_FUNCTION;
99  lock_holder &operator=(const lock_holder &) UTIL_CONFIG_DELETED_FUNCTION;
100 
101  private:
102  value_type *lock_flag_;
103  };
104 
105  template <typename TLock>
107  : public lock_holder<TLock, detail::default_read_lock_action<TLock>, detail::default_read_unlock_action<TLock> > {
108  public:
109  read_lock_holder(TLock &lock)
110  : lock_holder<TLock, detail::default_read_lock_action<TLock>, detail::default_read_unlock_action<TLock> >(lock) {}
111  };
112 
113  template <typename TLock>
115  : public lock_holder<TLock, detail::default_write_lock_action<TLock>, detail::default_write_unlock_action<TLock> > {
116  public:
117  write_lock_holder(TLock &lock)
118  : lock_holder<TLock, detail::default_write_lock_action<TLock>, detail::default_write_unlock_action<TLock> >(lock) {}
119  };
120  } // namespace lock
121 } // namespace util
122 
123 #endif /* _UTIL_LOCK_LOCK_HOLDER_H_ */
void operator()(TLock &lock) const
Definition: lock_holder.h:42
bool operator()(TLock &lock) const
Definition: lock_holder.h:29
bool is_available() const
Definition: lock_holder.h:95
value_type * lock_flag_
Definition: lock_holder.h:102
lock_holder(TLock &lock)
Definition: lock_holder.h:83