thread_safe_map.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. thread_safe_map()
  15. {}
  16. Val& operator [](const Key& key)
  17. {
  18. std::lock_guard<std::mutex> lk(mtx_);
  19. return dataMap_[key];
  20. }
  21. int erase(const Key& key )
  22. {
  23. std::lock_guard<std::mutex> lk(mtx_);
  24. return dataMap_.erase(key);
  25. }
  26. bool find_update(const Key& key,const Val& val)
  27. {
  28. std::lock_guard<std::mutex> lk(mtx_);
  29. if(dataMap_.find(key)!=dataMap_.end()) {
  30. dataMap_[key]=val;
  31. return true;
  32. }
  33. return false;
  34. }
  35. bool find(const Key& key)
  36. {
  37. std::lock_guard<std::mutex> lk(mtx_);
  38. if(dataMap_.find(key)!=dataMap_.end()) {
  39. return true;
  40. }
  41. return false;
  42. }
  43. bool find(const Key& key,Val& val)
  44. {
  45. std::lock_guard<std::mutex> lk(mtx_);
  46. if(dataMap_.find(key)!=dataMap_.end()) {
  47. val=dataMap_[key];
  48. return true;
  49. }
  50. return false;
  51. }
  52. /*this_iterator find( const Key& key )
  53. {
  54. std::lock_guard<std::mutex> lk(mtx_);
  55. return dataMap_.find(key);
  56. }
  57. this_const_iterator find( const Key& key ) const
  58. {
  59. std::lock_guard<std::mutex> lk(mtx_);
  60. return dataMap_.find(key);
  61. }*/
  62. this_iterator begin()
  63. {
  64. return dataMap_.begin();
  65. }
  66. this_iterator end()
  67. {
  68. return dataMap_.end();
  69. }
  70. this_const_iterator end() const
  71. {
  72. return dataMap_.end();
  73. }
  74. unsigned int size()
  75. {
  76. return dataMap_.size();
  77. }
  78. private:
  79. std::map<Key, Val> dataMap_;
  80. std::mutex mtx_;
  81. };
  82. #endif //NNXX_TESTS_THREAD_SAFE_MAP_H