64,281
社区成员
发帖
与我相关
我的任务
分享
boost::unordered_map<int,string> map;
....
string *Get(int key)
{
MapInt::iterator it = m_map_int.find(key); //查找迭代器
return (it == m_map_int.end()) ? NULL : &it->second; //值判断
}
boost::unordered_map<int,string> map;
boost::shared_mutex <m_mutex>; //锁定义
....
string *Get(int key)
{
boost::shared_lock lock( m_mutex ); //这边定义为读锁
MapInt::iterator it = m_map_int.find(key);
return (it == m_map_int.end()) ? NULL : &it->second;
}
boost::unordered_map<int,string> map;
boost::shared_mutex <m_mutex>; //锁定义
....
string Get(int key)
{
boost::shared_lock lock( m_mutex ); //这边定义为读锁
MapInt::iterator it = m_map_int.find(key);
return (it == m_map_int.end()) ? NULL : it->second;
}
struct value
{
string val;
int hash;
};
boost::unordered_map<int,value> map;
....
void Get(int key,string &str)
{
MapInt::iterator it = m_map_int.find(key);
str = it->second.val;
//这里用到"hash"函数得到值的hash值与写入时的hash值做比较,当无法匹配时说明其它线程正在写操作,这时可以适当"等待"后重新读取。
while(hash(str) != it->second.hash)
{
sleep(1);
it = m_map_int.find(key);
str = it->second.val;
}
}