添加线程安全map

master
ATTIOT\zhengcy 2021-10-09 11:06:33 +08:00
parent 2c9ede1eb7
commit cd9b8668dc
1 changed files with 54 additions and 0 deletions

View File

@ -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 <map>
#include <mutex>
template<typename Key, typename Val>
class ThreadSafeMap
{
public:
typedef typename std::map<Key, Val>::iterator this_iterator;
typedef typename std::map<Key, Val>::const_iterator this_const_iterator;
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);
}
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 end()
{
return dataMap_.end();
}
this_const_iterator end() const
{
return dataMap_.end();
}
private:
std::map<Key, Val> dataMap_;
std::mutex mtx_;
};