thread_safe_map.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 end()
  61. {
  62. return dataMap_.end();
  63. }
  64. this_const_iterator end() const
  65. {
  66. return dataMap_.end();
  67. }
  68. unsigned int size()
  69. {
  70. return dataMap_.size();
  71. }
  72. private:
  73. std::map<Key, Val> dataMap_;
  74. std::mutex mtx_;
  75. };
  76. #endif //NNXX_TESTS_THREAD_SAFE_MAP_H