diff --git a/general/src/threadsafe/threadsafe_map.hpp b/general/src/threadsafe/threadsafe_map.hpp new file mode 100644 index 0000000..1994a5a --- /dev/null +++ b/general/src/threadsafe/threadsafe_map.hpp @@ -0,0 +1,54 @@ +/* + * @Author: your name + * @Date: 2021-10-09 10:27:31 + * @LastEditTime: 2021-10-09 10:53:33 + * @LastEditors: Please set LastEditors + * @Description: In User Settings Edit + * @FilePath: \test_algorithm\threadsafe_map.hpp + */ + +#include +#include + +template +class ThreadSafeMap +{ +public: + typedef typename std::map::iterator this_iterator; + typedef typename std::map::const_iterator this_const_iterator; + Val& operator [](const Key& key) + { + std::lock_guard lk(mtx_); + return dataMap_[key]; + } + int erase(const Key& key ) + { + std::lock_guard lk(mtx_); + return dataMap_.erase(key); + } + + this_iterator find( const Key& key ) + { + std::lock_guard lk(mtx_); + return dataMap_.find(key); + } + this_const_iterator find( const Key& key ) const + { + std::lock_guard lk(mtx_); + return dataMap_.find(key); + } + + this_iterator end() + { + return dataMap_.end(); + } + + this_const_iterator end() const + { + return dataMap_.end(); + } + +private: + std::map dataMap_; + std::mutex mtx_; +};