map的并发操作是不安全的,C++里边有红黑树实现的std::map和hash表 unordered_map。
在《C++并发编程实战》一书中的162页提供了一个细粒度锁的MAP数据结构。
使用了 boost的shared_mutex (C++14已经支持,C++11没有)
使用了std::hash
大家可以参考这本书的实现,如果支持C++14的话可以不用boost。
我这里简单写一个对std::map整个数据结构加锁的简单的类,我是在自己写一些测试demo的时候可能会用。
#ifndef SAFE_MAP_H_
#define SAFE_MAP_H_
///< 不是最优的方案,因为锁住了整个数据结构
#include <map>
#include <mutex>
template<typename Key, typename Val>
class SafeMap
{
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_;
};
#endif //SAFE_MAP_H_