采用精细粒度锁操作的map数据结构
为了容纳精细粒度锁操作, 需谨慎考察数据结构的底层细节, 而不是将一个现成的容器包装起来, 这里std::map<>并不合适
散列表实现查找表 threadsafe_lookup_table
实现如下
class threadsafe_lookup_table
{
private:
class bucket_type
{
private:
using bucket_value = pair<Key, Value>;
using bucket_data = list<bucket_value>;
using bucket_iterator = typename bucket_data::iterator ;
using bucket_const_iterator = typename bucket_data::const_iterator ;
bucket_data data;
mutable shared_mutex m;
bucket_const_iterator find_entry_for(Key const &key) const
{
return find_if(data.begin(), data.end(),[&](bucket_value const &item){return item.first == key;});
}
bucket_iterator find_entry_for(Key const &key)
{
return find_if(data.begin(), data.end(),[&](bucket_value const &item){return item.first == key;});
}
public:
Value value_for(Key const&key,Value const&default_value) const
{
shared_lock lock1(m);
bucket_const_iterator found_entry= find_entry_for(key);
return (found_entry==data.end())?default_value:found_entry->second;
}
void add_or_update_mapping(Key const&key ,Value const&value)
{
unique_lock lock1(m);
bucket_iterator const found_entry=find_entry_for(key);
if(found_entry==data.end())
{
data.push_back(bucket_value(key,value));
}
else
found_entry->second=value;
}
void remove_mapping(Key const&key)
{