包装了一个多线程安全的hash_map(好用),欢迎指点
class __buddy; // not implement
template<class Key,class Type,class Buddy = __buddy>
class simp_hash_map{
private:
typedef bool (Buddy::*Function)(Type& _val);
simp_hash_map(const simp_hash_map &);
simp_hash_map& operator=(const simp_hash_map &);
stdext::hash_map<Key,Type> _map;
// 因为可能出现在apply函数中erase某个元素的情况,
// 这样,如果_ite作为apply函数的变量,就可能指向一
// 个未知的地方,所以把_ite作为类变量,方便处理
typename stdext::hash_map<Key,Type>::iterator _ite;
CriticalSection _cs;
public:
simp_hash_map(){
_ite = _map.begin();
}
~simp_hash_map(){
}
bool insert(const Key& _key,const Type& _val){
CriticalSectionLock lock(_cs);
return _map.insert(std::pair<Key,Type>(_key,_val)).second;
}
int erase(const Key& _key){
CriticalSectionLock lock(_cs);
if(_ite != _map.end() && _ite->first == _key ){
_ite = _map.erase(_ite);
return 1;
}else{
return _map.erase(_key);
}
}
void clear(){
CriticalSectionLock lock(_cs);
_map.clear();
_ite = _map.begin();
}
bool find(const Key& _key,Type& _val){
CriticalSectionLock lock(_cs);
stdext::hash_map<Key,Type>::const_iterator _ite = _map.find(_key);
if( _ite == _map.end() )return false;
_val = _ite->second;
return true;
}
bool apply(Function _fun,Buddy * const _buddy){
CriticalSectionLock lock(_cs);
_ite = _map.begin();
while( _ite != _map.end()){
Type& _tval = _ite->second;
++_ite;
// 如果先_fun, 然后++_ite, 如果_fun
// erase掉当前的_ite,就漏掉当前_ite
// 的后一个元素,没有在上面执行_fun
if( (_buddy->*_fun)(_tval) )return true;
}
return false;
}
int size(){
CriticalSectionLock lock(_cs);
return _map.size();
}
};
下面是测试程序
class a{
public:
a(){
_map.insert(0,0);
_map.insert(1,1);
_map.insert(2,2);
_map.insert(3,3);
j = 5;
}
int j;
simp_hash_map<int,int,a> _map;
bool foo(int& _i){
_map.erase(_i + 1);
return false;
}
bool fox(int& _i){
printf("%d\n",_i);
return false;
}
void bar(){
_map.apply(foo,this);
_map.apply(fox,this);
}
};
int main(){
a _a;
_a.bar();
return 0;
}