Digitalisierte Elektroverteilung zur permanenten Verbraucherüberwachung
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ts_map.h 1.9KB

3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #ifndef TS_MAP_H
  2. #define TS_MAP_H
  3. #pragma once
  4. #include <map>
  5. #include <mutex>
  6. #include <condition_variable>
  7. template <typename KEY, typename VALUE>
  8. class ts_map
  9. {
  10. public:
  11. ts_map() = default;
  12. ts_map(const ts_map<KEY, VALUE>&) = delete;
  13. virtual ~ts_map() { clear(); }
  14. public:
  15. void emplaceOrOverwrite(KEY key, VALUE value){
  16. std::scoped_lock lock(muxMap);
  17. auto it = map.find(key);
  18. if(it != map.end()){
  19. it->second = value;
  20. }
  21. else{
  22. map.emplace(key, value);
  23. }
  24. }
  25. void emplace(KEY key, VALUE&& value){
  26. std::scoped_lock lock(muxMap);
  27. map.emplace(key, std::move(value));
  28. }
  29. auto find(KEY key){
  30. std::scoped_lock lock(muxMap);
  31. return map.find(key);
  32. }
  33. // Returns true if Queue has no items
  34. bool empty()
  35. {
  36. std::scoped_lock lock(muxMap);
  37. return map.empty();
  38. }
  39. // Returns number of items in Queue
  40. size_t size()
  41. {
  42. std::scoped_lock lock(muxMap);
  43. return map.size();
  44. }
  45. // Clears Queue
  46. void clear()
  47. {
  48. std::scoped_lock lock(muxMap);
  49. std::map<KEY, VALUE> empty;
  50. std::swap(map, empty);
  51. }
  52. void wait()
  53. {
  54. while (empty())
  55. {
  56. std::unique_lock<std::mutex> ul(muxBlocking);
  57. cvBlocking.wait(ul);
  58. }
  59. }
  60. auto begin() const{
  61. return map.begin();
  62. }
  63. auto end() const{
  64. return map.end();
  65. }
  66. protected:
  67. std::mutex muxMap;
  68. std::map<KEY, VALUE> map;
  69. std::condition_variable cvBlocking;
  70. std::mutex muxBlocking;
  71. };
  72. #endif // TS_MAP_H