BeeeOn Gateway  v2020.3.1-2-g6f737dc
Platform to interconnect the IoT world
HashedLock.h
1 #pragma once
2 
3 #include <Poco/Exception.h>
4 #include <Poco/SharedPtr.h>
5 
6 #include <vector>
7 
8 namespace BeeeOn {
9 
38 template <typename LockType, typename ID, typename Hash = typename ID::Hash>
39 class HashedLock {
40 public:
41  typedef LockType Lock;
42  typedef Poco::SharedPtr<HashedLock<Lock, ID, Hash>> Ptr;
43 
48  HashedLock();
49 
53  HashedLock(unsigned int count);
54 
60  void delayedInit(unsigned int count);
61 
66  Lock &find(const ID &id);
67 
71  Lock &at(const unsigned int index);
72 
76  unsigned int size() const;
77 
78 protected:
79  void assureInitialized();
80 
81 private:
82  std::vector<Lock> m_lock;
83 };
84 
85 template <typename Lock, typename ID, typename Hash>
87  HashedLock<Lock, ID, Hash>(0)
88 {
89 }
90 
91 template <typename Lock, typename ID, typename Hash>
93  m_lock(count)
94 {
95 }
96 
97 template <typename Lock, typename ID, typename Hash>
99 {
100  if (count == 0) {
101  throw Poco::InvalidArgumentException(
102  "HashedLock must be initialized by non-zero count of locks");
103  }
104 
105  if (m_lock.empty()) {
106  m_lock = std::vector<Lock>(count);
107  }
108  else {
109  throw Poco::InvalidAccessException(
110  "delayedInit() can be called only once");
111  }
112 }
113 
114 template <typename Lock, typename ID, typename Hash>
116 {
117  assureInitialized();
118 
119  Hash hash;
120  const unsigned int index = hash(id) % size();
121  return at(index);
122 }
123 
124 template <typename Lock, typename ID, typename Hash>
125 Lock &HashedLock<Lock, ID, Hash>::at(const unsigned int index)
126 {
127  assureInitialized();
128  return m_lock[index];
129 }
130 
131 template <typename Lock, typename ID, typename Hash>
133 {
134  return m_lock.size();
135 }
136 
137 template <typename Lock, typename ID, typename Hash>
139 {
140  if (m_lock.empty()) {
141  throw Poco::IllegalStateException(
142  "HashedLock has not been initialized yet");
143  }
144 }
145 
146 }
unsigned int size() const
Definition: HashedLock.h:132
Lock & at(const unsigned int index)
Definition: HashedLock.h:125
HashedLock()
Definition: HashedLock.h:86
Definition: HashedLock.h:39
Lock & find(const ID &id)
Definition: HashedLock.h:115
void delayedInit(unsigned int count)
Definition: HashedLock.h:98