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_