thread_safe_map.h 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. //
  2. // Created by zx on 2020/7/3.
  3. //
  4. #ifndef NNXX_TESTS_THREAD_SAFE_MAP_H
  5. #define NNXX_TESTS_THREAD_SAFE_MAP_H
  6. #include <map>
  7. #include <mutex>
  8. template<typename Key, typename Val>
  9. class thread_safe_map
  10. {
  11. public:
  12. typedef typename std::map<Key, Val>::iterator this_iterator;
  13. typedef typename std::map<Key, Val>::const_iterator this_const_iterator;
  14. Val& operator [](const Key& key)
  15. {
  16. std::lock_guard<std::mutex> lk(mtx_);
  17. return dataMap_[key];
  18. }
  19. int erase(const Key& key )
  20. {
  21. std::lock_guard<std::mutex> lk(mtx_);
  22. return dataMap_.erase(key);
  23. }
  24. this_iterator find( const Key& key )
  25. {
  26. std::lock_guard<std::mutex> lk(mtx_);
  27. return dataMap_.find(key);
  28. }
  29. this_const_iterator find( const Key& key ) const
  30. {
  31. std::lock_guard<std::mutex> lk(mtx_);
  32. return dataMap_.find(key);
  33. }
  34. this_iterator end()
  35. {
  36. return dataMap_.end();
  37. }
  38. this_const_iterator end() const
  39. {
  40. return dataMap_.end();
  41. }
  42. private:
  43. std::map<Key, Val> dataMap_;
  44. std::mutex mtx_;
  45. };
  46. #endif //NNXX_TESTS_THREAD_SAFE_MAP_H