rad  5.1.0
doubleMap.hpp
Go to the documentation of this file.
1 
9 #ifndef RAD_DOUBLE_MAP_HPP
10 #define RAD_DOUBLE_MAP_HPP
11 
12 #include <string>
13 #include <map>
14 #include <mutex>
15 
16 namespace rad {
17 
18 
52 template <typename T>
53 class DoubleMap {
54 public:
58  DoubleMap() : m_kv_write_index(0) {
59  }
60 
64  virtual ~DoubleMap() {}
65 
74  void Reset() {
75  std::lock_guard<std::mutex> lock(m_mutex);
76  m_kv[0].clear();
77  m_kv[1].clear();
78  m_kv_write_index = 0;
79  }
80 
91  void Set(const std::string& key, const T& value) {
92  std::lock_guard<std::mutex> lock(m_mutex);
93  m_kv[m_kv_write_index][key] = value;
94  }
95 
106  void Set(const std::map<std::string, T>& kv_map) {
107  std::lock_guard<std::mutex> lock(m_mutex);
108  for(auto& kv : kv_map) {
109  m_kv[m_kv_write_index][kv.first] = kv.second;
110  }
111  }
112 
123  void Pop(std::map<std::string, T>& kv_map) {
124  /*
125  * Swap read/write maps.
126  */
127  int kv_read_index = m_kv_write_index;
128  {
129  std::lock_guard<std::mutex> lock(m_mutex);
130  if (m_kv_write_index == 0) {
131  m_kv_write_index = 1;
132  } else {
133  m_kv_write_index = 0;
134  }
135  }
136 
137  /*
138  * Copy the key/value pairs.
139  */
140  kv_map = m_kv[kv_read_index];
141 
142  /*
143  * Clear the buffer to avoid returning again old
144  * attributes/values already processed by the
145  * consumer.
146  */
147  m_kv[kv_read_index].clear();
148  }
149 
153  DoubleMap(const DoubleMap&) = delete;
154 
158  DoubleMap& operator=(const DoubleMap&) = delete;
159 
160 private:
161  std::mutex m_mutex;
162  std::map<std::string, T> m_kv[2];
163  int m_kv_write_index;
164 };
165 
166 } // namespace rad
167 
168 #endif // RAD_DOUBLE_MAP_HPP
Definition: doubleMap.hpp:53
virtual ~DoubleMap()
Definition: doubleMap.hpp:64
DoubleMap & operator=(const DoubleMap &)=delete
void Pop(std::map< std::string, T > &kv_map)
Definition: doubleMap.hpp:123
void Set(const std::map< std::string, T > &kv_map)
Definition: doubleMap.hpp:106
void Set(const std::string &key, const T &value)
Definition: doubleMap.hpp:91
DoubleMap()
Definition: doubleMap.hpp:58
void Reset()
Definition: doubleMap.hpp:74
DoubleMap(const DoubleMap &)=delete
Definition: actionsApp.cpp:20