栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

Redis源码学习(31),字典学习,dict.c(一)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Redis源码学习(31),字典学习,dict.c(一)

1 dictCreate 1.1 方法说明

  创建一个新的 hash table

1.2 方法源码
	
	dict *dictCreate(dictType *type,
	        void *privDataPtr)
	{
	    dict *d = zmalloc(sizeof(*d));//分配内存
	
	    _dictInit(d,type,privDataPtr);//字典初始化
	    
	    return d;
	}
1.3 相关方法 1.3.1 _dictInit
	
	int _dictInit(dict *d, dictType *type,
	        void *privDataPtr)
	{
	    _dictReset(&d->ht[0]);
	    _dictReset(&d->ht[1]);
	    d->type = type;
	    d->privdata = privDataPtr;
	    d->rehashidx = -1;
	    d->iterators = 0;
	    return DICT_OK;
	}
1.3.2 _dictReset
	
	static void _dictReset(dictht *ht)
	{
	    ht->table = NULL;
	    ht->size = 0;
	    ht->sizemask = 0;
	    ht->used = 0;
	}
1.4 代码理解
  1. 先申明一个字典结构体,并分配相应内存。
  2. 调用 _dictInit 初始化字典。
  3. 调用 _dictReset 初始化字典中两个哈希表。
  4. 将哈希表中几个属性字段都设置为初始值。
2 dictAdd 2.1 方法说明

  增加一个哈希节点到哈希表中。

2.2 方法源码
int dictAdd(dict *d, void *key, void *val)
{
    dictEntry *entry = dictAddRaw(d,key);

    if (!entry) return DICT_ERR;
    dictSetVal(d, entry, val);
    return DICT_OK;
}


2.3 相关代码 2.3.1 dictAddRaw
dictEntry *dictAddRaw(dict *d, void *key)
{
    int index;
    dictEntry *entry;
    dictht *ht;
	
	// 如果字典在进行 rahase 中,则进行一步 rahash
    if (dictIsRehashing(d)) _dictRehashStep(d);

    
    // 获取建的索引
    if ((index = _dictKeyIndex(d, key)) == -1)
        return NULL;

    
    // 如果在 rehash 中 则返回第二个 hash 表中
    // 将新的哈希节点加入第二个 hash 表中
    ht = dictIsRehashing(d) ? &d->ht[1] : &d->ht[0];
    entry = zmalloc(sizeof(*entry));
    entry->next = ht->table[index];
    ht->table[index] = entry;
    ht->used++;

    
    //设置哈希建
    dictSetKey(d, entry, key);
    return entry;
}
2.3.2 _dictKeyIndex
static int _dictKeyIndex(dict *d, const void *key)
{
    unsigned int h, idx, table;
    dictEntry *he;

    
    if (_dictExpandIfNeeded(d) == DICT_ERR)
        return -1;
    
    h = dictHashKey(d, key);
    for (table = 0; table <= 1; table++) {
        idx = h & d->ht[table].sizemask;
        
        he = d->ht[table].table[idx];
        while(he) {
            if (dictCompareKeys(d, key, he->key))
                return -1;
            he = he->next;
        }
        if (!dictIsRehashing(d)) break;
    }
    return idx;
}
2.4 代码理解
  1. 调用 dictAddRaw 增加一个哈希节点
  2. 计算键的索引值,如果该值已经存在则返回错误
  3. 如果正在进行 rehash 的话,会向第二个哈希表中新增节点
  4. 调用宏定义方法 dictSetKey 设置哈希节点的键
  5. 调用宏定义方法 dictSetVal 设置哈希节点的值
3 学习总结
  1. 增加新的哈希节点的时候,如果节点已存在则会报错。
  2. 调用 dictHashKey 计算键的哈希值。
  3. 再用哈希值与字典掩码计算出索引位置。
  4. 遍历两个哈希表,判断键是否已存在。
  5. 如果字典正在 rehash 中的话,则新增的节点会加到第二个哈希表中。
  6. 如果字典正在 rehash 中的话, 则会进行一步的 rehash 的动作。
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1001433.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号