123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- //
- // Created by zx on 2020/7/3.
- //
- #ifndef NNXX_TESTS_THREAD_SAFE_MAP_H
- #define NNXX_TESTS_THREAD_SAFE_MAP_H
- #include <map>
- #include <mutex>
- template<typename Key, typename Val>
- class thread_safe_map
- {
- public:
- typedef typename std::map<Key, Val>::iterator this_iterator;
- typedef typename std::map<Key, Val>::const_iterator this_const_iterator;
- thread_safe_map()
- {}
- Val& operator [](const Key& key)
- {
- std::lock_guard<std::mutex> lk(mtx_);
- return dataMap_[key];
- }
- int erase(const Key& key )
- {
- std::lock_guard<std::mutex> lk(mtx_);
- return dataMap_.erase(key);
- }
- bool find_update(const Key& key,const Val& val)
- {
- std::lock_guard<std::mutex> lk(mtx_);
- if(dataMap_.find(key)!=dataMap_.end()) {
- dataMap_[key]=val;
- return true;
- }
- return false;
- }
- bool find(const Key& key)
- {
- std::lock_guard<std::mutex> lk(mtx_);
- if(dataMap_.find(key)!=dataMap_.end()) {
- return true;
- }
- return false;
- }
- bool find(const Key& key,Val& val)
- {
- std::lock_guard<std::mutex> lk(mtx_);
- if(dataMap_.find(key)!=dataMap_.end()) {
- val=dataMap_[key];
- return true;
- }
- return false;
- }
- /*this_iterator find( const Key& key )
- {
- std::lock_guard<std::mutex> lk(mtx_);
- return dataMap_.find(key);
- }
- this_const_iterator find( const Key& key ) const
- {
- std::lock_guard<std::mutex> lk(mtx_);
- return dataMap_.find(key);
- }*/
- this_iterator begin()
- {
- return dataMap_.begin();
- }
- this_iterator end()
- {
- return dataMap_.end();
- }
- this_const_iterator end() const
- {
- return dataMap_.end();
- }
- unsigned int size()
- {
- return dataMap_.size();
- }
- private:
- std::map<Key, Val> dataMap_;
- std::mutex mtx_;
- };
- #endif //NNXX_TESTS_THREAD_SAFE_MAP_H
|