thread_safe_map.h 1.9 KB

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