libcopp  1.1.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 
22 namespace util {
23  namespace lock {
24  namespace detail {
25  template <typename TLock>
27  bool operator()(TLock &lock) const {
28  lock.lock();
29  return true;
30  }
31  };
32 
33  template <typename TLock>
35  bool operator()(TLock &lock) const { return lock.try_lock(); }
36  };
37 
38  template <typename TLock>
40  void operator()(TLock &lock) const { lock.unlock(); }
41  };
42 
43  template <typename TLock>
45  bool operator()(TLock &lock) const { return lock.try_unlock(); }
46  };
47  }
48 
49  template <typename TLock, typename TLockAct = detail::default_lock_action<TLock>,
50  typename TUnlockAct = detail::default_unlock_action<TLock> >
51  class lock_holder {
52  public:
53  typedef TLock value_type;
54 
55  lock_holder(TLock &lock) : lock_flag_(&lock) {
56  if (false == TLockAct()(lock)) {
57  lock_flag_ = NULL;
58  }
59  }
60 
62  if (NULL != lock_flag_) {
63  TUnlockAct()(*lock_flag_);
64  }
65  }
66 
67  bool is_available() const { return NULL != lock_flag_; }
68 
69  private:
70  lock_holder(const lock_holder &);
71  lock_holder &operator=(const lock_holder &);
72 
73  private:
74  value_type *lock_flag_;
75  };
76  }
77 }
78 
79 #endif /* _UTIL_LOCK_LOCK_HOLDER_H_ */
void operator()(TLock &lock) const
Definition: lock_holder.h:40
bool operator()(TLock &lock) const
Definition: lock_holder.h:27
bool is_available() const
Definition: lock_holder.h:67
value_type * lock_flag_
Definition: lock_holder.h:74
lock_holder(TLock &lock)
Definition: lock_holder.h:55