ThreadSafeMap.h 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. // David Eberly, Geometric Tools, Redmond WA 98052
  2. // Copyright (c) 1998-2020
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // https://www.boost.org/LICENSE_1_0.txt
  5. // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
  6. // Version: 4.0.2019.08.13
  7. #pragma once
  8. #include <map>
  9. #include <mutex>
  10. #include <vector>
  11. namespace WwiseGTE
  12. {
  13. template <typename Key, typename Value>
  14. class ThreadSafeMap
  15. {
  16. public:
  17. // Construction and destruction.
  18. ThreadSafeMap() = default;
  19. virtual ~ThreadSafeMap() = default;
  20. // All the operations are thread-safe.
  21. bool HasElements() const
  22. {
  23. bool hasElements;
  24. mMutex.lock();
  25. {
  26. hasElements = (mMap.size() > 0);
  27. }
  28. mMutex.unlock();
  29. return hasElements;
  30. }
  31. bool Exists(Key key) const
  32. {
  33. bool exists;
  34. mMutex.lock();
  35. {
  36. exists = (mMap.find(key) != mMap.end());
  37. }
  38. mMutex.unlock();
  39. return exists;
  40. }
  41. void Insert(Key key, Value value)
  42. {
  43. mMutex.lock();
  44. {
  45. mMap[key] = value;
  46. }
  47. mMutex.unlock();
  48. }
  49. bool Remove(Key key, Value& value)
  50. {
  51. bool exists;
  52. mMutex.lock();
  53. {
  54. auto iter = mMap.find(key);
  55. if (iter != mMap.end())
  56. {
  57. value = iter->second;
  58. mMap.erase(iter);
  59. exists = true;
  60. }
  61. else
  62. {
  63. exists = false;
  64. }
  65. }
  66. mMutex.unlock();
  67. return exists;
  68. }
  69. void RemoveAll()
  70. {
  71. mMutex.lock();
  72. {
  73. mMap.clear();
  74. }
  75. mMutex.unlock();
  76. }
  77. bool Get(Key key, Value& value) const
  78. {
  79. bool exists;
  80. mMutex.lock();
  81. {
  82. auto iter = mMap.find(key);
  83. if (iter != mMap.end())
  84. {
  85. value = iter->second;
  86. exists = true;
  87. }
  88. else
  89. {
  90. exists = false;
  91. }
  92. }
  93. mMutex.unlock();
  94. return exists;
  95. }
  96. void GatherAll(std::vector<Value>& values) const
  97. {
  98. mMutex.lock();
  99. {
  100. if (mMap.size() > 0)
  101. {
  102. values.resize(mMap.size());
  103. auto viter = values.begin();
  104. for (auto const& m : mMap)
  105. {
  106. *viter++ = m.second;
  107. }
  108. }
  109. else
  110. {
  111. values.clear();
  112. }
  113. }
  114. mMutex.unlock();
  115. }
  116. protected:
  117. std::map<Key, Value> mMap;
  118. mutable std::mutex mMutex;
  119. };
  120. }