c++多线程进阶(7): 采用锁的数据结构之threadsafe_lookup_table, threadsafe_list

采用精细粒度锁操作的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)
        {
           
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值