资讯专栏INFORMATION COLUMN

Redis3.2源码分析-字典dict

_ang / 1438人阅读

摘要:里存放的是一堆工具函数的函数指针,保存中的某些函数需要作为参数的数据两个,平时用,时用当前到的哪个索引,时表示非状态安全迭代器的计数。迭代器的定义先不管,等下文讲到安全非安全迭代器的时候再细说。

最近工作有点忙,拖了好久才挤出时间学习dict源码。还是希望能坚持读下去。

先简单介绍一下redis字典

字典的目的是为了通过某个信息(key) 找到另一个信息(value)。为了快速从key找到value,字典通常会用hash表作为底层的存储,redis的字典也不例外,它的实现是基于时间复杂度为O(1)的hash算法(关于hash表的介绍可以参考《算法导论》"散列表"一章)
redis中字典的主要用途有以下两个:

1.实现数据库键空间(key space);
2.用作 Hash 类型键的底层实现之一;

第一种情况:因为redis是基于key-val的存储系统,整个db的键空间就是一个大字典,这个字典里放了许多key-val对,不论value是String、List、Hash、Set、Zset中的哪种类型,redis都会根据每个key生成一个字典的索引
第二种情况:若value的类型是Redis中的Hash,在Hash数据量较大的情况下 redis会将Hash中的每个field也当作key生成一个字典(出于性能考虑,Hash数据量小的时候redis会使用压缩列表ziplist来存Hash的filed),最终 Hash的key是一个字典的索引,key中的所有field又分别是另一个字典的索引。

redis中dict的定义

上图的结构是dict.h文件的整个蓝图
首先从上图能看出 redis解决hash冲突的方法用的是链地址法,将冲突的键值对按照一个单向链表来存储,每个底层的key-val节点都是一个链表节点。

dictEntry

看看单个key-val节点结构声明的代码:

typedef struct dictEntry {
    void *key;
    union {
        void *val;
        uint64_t u64;
        int64_t s64;
        double d;
    } v;
    struct dictEntry *next;//下一个节点的地址
} dictEntry;

没什么可说的,就是一个链表节点的声明,节点里存了key、value以及下一个节点的指针(下文直接用"dictEntry"指代"key-val节点")。因为value有多种类型,所以value用了union来存储,c语言的union总结起来就是两句话: In union, all members share the same memory location...Size of a union is taken according the size of largest member in union.(union的所有成员共享同一块内存,union的size取决于它的最大的成员的size)

dictht

通常实现一个hash表时会使用一个buckets存放dictEntry的地址,将key代入hash函数得到的值就是buckets的索引,这个值决定了我们要将此dictEntry节点放入buckets的哪个索引里。这个buckets实际上就是我们说的hash表。
这个buckets存储在哪里呢?
dict.h的dictht结构中table存放的就是buckets的地址。以下是dictht的声明:

typedef struct dictht {
    dictEntry **table;//buckets的地址
    unsigned long size;//buckets的大小,总保持为 2^n
    unsigned long sizemask;//掩码,用来计算hash值对应的buckets索引
    unsigned long used;//当前dictht有多少个dictEntry节点
} dictht;

成员变量used:要注意 used跟size没有任何关系,这是当前dictht包含多少个dictEntry节点的意思,渐进rehash(下文会详细介绍rehash)时会用这个成员判断是否已经rehash完成,而size是buckets的大小。
成员变量sizemask:key通过hash函数得到的hash值 跟 sizemask 作"与运算",得到的值就是这个key需要放入的buckets的索引:

h = dictHashKey(d, de->key) & d->ht[0].sizemask

d->ht[0].table[h]就是这个dictEntry该放入的地方。这应该也是bucekts大小总保持2^n的原因,方便通过hash值与sizemask得到索引。

dict

上面说了,dictht实际上就是hash表的核心,但是只有一个dictht很多事情还做不了,所以redis定义了一个叫dict的结构以支持字典的各种操作,如rehash和遍历hash等。

typedef struct dict {
    dictType *type;//dictType里存放的是一堆工具函数的函数指针,
    void *privdata;//保存type中的某些函数需要作为参数的数据
    dictht ht[2];//两个dictht,ht[0]平时用,ht[1] rehash时用
    long rehashidx; /* rehashing not in progress if rehashidx == -1 *///当前rehash到buckets的哪个索引,-1时表示非rehash状态
    int iterators; /* number of iterators currently running *///安全迭代器的计数。
} dict;

迭代器的定义先不管,等下文讲到安全非安全迭代器的时候再细说。

hash算法

redis内置3种hash算法

dictIntHashFunction,对正整数进行hash

dictGenHashFunction,对字符串进行hash

dictGenCaseHashFunction,对字符串进行hash,不区分大小写

这些hash函数没什么好说的,有兴趣google一下就好。
在讲redis字典基本操作之前,有必要介绍一下rehash,因为dict的增删改查(CRUD)都会执行被动rehash。

rehash 什么是rehash

当字典的dictEntry节点扩展到一定规模时,hash冲突的链表会越来越长,使原本O(1)的hash运算转换成了O(n)的链表遍历,从而导致字典的增删改查(CRUD)越来越低效,这个时候redis会利用dict结构中的dictht[1]扩充一个新的buckets(调用dictExpand),然后慢慢将dictht[0]的节点迁移至dictht[1]、用dictht[1]替换掉dictht[0] (调用dictRehash)。
具体扩充过程如下:

1.调用dictAdd为dict添加一个dictEntry节点。

2.调用_dictKeyIndex找到应该放置在buckets的哪个索引里。顺便调用_dictExpandIfNeeded判断是否需要扩充 dictht[1]。

3.若满足条件:dictht[0]的dictEntry节点数/buckets的索引数>=1则调用dictExpand,若dictEntry节点数/buckets的索引数>=dict_force_resize_ratio(默认是5),则强制执行dictExpand扩充dictht[1]。

需要注意的是上面的条件不是rehash的条件,而是扩充dictht[1]并打开dict rehash开关的条件。(因为rehash不是一次性完成的,若dictEntry节点非常多,rehash过程会进行很久从而block其他操作。所以redis采用了渐进rehash,分步进行,下文讲rehash方式时会详细介绍)。dictExpand做的只是把dictht[1]的buckets扩充到合适的大小,再把dict的rehashidx从-1置为0(打开rehash开关)。打开rehash开关之后该dict每次增删改查(CRUD)都会执行一次rehash,把dictht[0]的buckets中的一个索引里的链表移动到dictht[1]。rehash的条件是rehashidx是否为-1。
放源码:

static int dict_can_resize = 1; 
static unsigned int dict_force_resize_ratio = 5; 

//判断dictht[1]是否需要扩充(并将dict调整为正在rehash状态);若dict刚创建,则扩充dictht[0]  
static int _dictExpandIfNeeded(dict *d)
{
    /* Incremental rehashing already in progress. Return. */
    if (dictIsRehashing(d)) return DICT_OK;

    /* If the hash table is empty expand it to the initial size. */
    //这是为刚创建的dict准备的,d->ht[0].size == 0时调用dictExpand只会扩充dictht[0],不会改变dict的rehash状态
    if (d->ht[0].size == 0) return dictExpand(d, DICT_HT_INITIAL_SIZE);

    /* If we reached the 1:1 ratio, and we are allowed to resize the hash
     * table (global setting) or we should avoid it but the ratio between
     * elements/buckets is over the "safe" threshold, we resize doubling
     * the number of buckets. */
    if (d->ht[0].used >= d->ht[0].size &&
        (dict_can_resize ||
         d->ht[0].used/d->ht[0].size > dict_force_resize_ratio))
    {
        //1:1时如果全局变量dict_can_resize为1则expand,
        //或者节点数/bucket数超过dict_force_resize_ratio(5)则扩充
        return dictExpand(d, d->ht[0].used*2);buckets大小扩充至 dict已使用节点的2倍的下一个2^n。假如used=4,buckets会扩充到8;used=5,buckets会扩充到16
    }
    return DICT_OK;
}

/* Expand or create the hash table */
//三个功能:
//1.为刚初始化的dict的dictht[0]分配table(buckets)
//2.为已经达到rehash要求的dict的dictht[1]分配一个更大(下一个2^n)的table(buckets),并将rehashidx置为0
//3.为需要缩小bucket的dict分配一个更小的buckets,并将rehashidx置为0(打开rehash开关)
int dictExpand(dict *d, unsigned long size)
{
    dictht n; /* the new hash table *///最终会赋值给d->ht[0]和d->ht[1],所以不用new一个dictht
    unsigned long realsize = _dictNextPower(size);//从4开始找大于等于size的最小2^n作为新的slot数量

    /* the size is invalid if it is smaller than the number of
     * elements already inside the hash table */
    if (dictIsRehashing(d) || d->ht[0].used > size)//如果当前使用的bucket数目大于想扩充之后的size
        return DICT_ERR;

    /* Rehashing to the same table size is not useful. */
    if (realsize == d->ht[0].size) return DICT_ERR;

    /* Allocate the new hash table and initialize all pointers to NULL */
    n.size = realsize;
    n.sizemask = realsize-1;
    n.table = zcalloc(realsize*sizeof(dictEntry*));
    n.used = 0;

    /* Is this the first initialization? If so it"s not really a rehashing
     * we just set the first hash table so that it can accept keys. */
    if (d->ht[0].table == NULL) {//刚创建的dict
        d->ht[0] = n;//为d->ht[0]赋值
        return DICT_OK;
    }

    /* Prepare a second hash table for incremental rehashing */
    d->ht[1] = n;
    d->rehashidx = 0;//设置rehash状态为正在进行rehash
    return DICT_OK;
}

画图分析一下扩充流程:
假设一个dict已经有4个dictEntry节点(value分别为"a","b","c","d"),根据key的不同,存放在buckets的不同索引下。

现在如果我们想添加一个dictEntry,由于d->ht[0].used >= d->ht[0].size (4>=4),满足了扩充dictht[1]的条件,会执行dictExpand。根据扩充规则,dictht[1]的buckets会扩充到8个槽位。

之后再将要添加的dictEntry加入到dictht[1]的buckets中的某个索引下,不过这个操作不属于dictExpand,不展开了。
扩充之后的dict的成员变量rehashidx被赋值为0,此后每次CRUD都会执行一次被动rehash把dictht[0]的buckets中的一个链表迁移到dictht[1]中,直到迁移完毕。

rehash的方式

刚才提到了被动rehash,实际上dict的rehash分为两种方式:

主动方式:调用dictRehashMilliseconds执行一毫秒。在redis的serverCron里调用,看名字就知道是为redis服务端准备的定时事件,每次执行1ms的dictRehash,简单粗暴。。

被动方式:字典的增删改查(CRUD)调用dictAdd,dicFind,dictDelete,dictGetRandomKey等函数时,会调用_dictRehashStep,迁移buckets中的一个非空bucket。

放上源码:

int dictRehashMilliseconds(dict *d, int ms) {
    long long start = timeInMilliseconds();
    int rehashes = 0;

    while(dictRehash(d,100)) {//每次最多执行buckets的100个链表rehash
        rehashes += 100;
        if (timeInMilliseconds()-start > ms) break;//最多执行ms毫秒
    }
    return rehashes;
}
static void _dictRehashStep(dict *d) {//只rehash一个bucket
    //没有安全迭代器绑定在当前dict上时才能rehash,下文讲"安全迭代器"时会细说,这里只需要知道这是rehash buckets的1个链表
    if (d->iterators == 0) dictRehash(d,1);
}

上面可以看出,不论是哪种rehash方式,底层都是通过dictRehash实现的,它是字典rehash的核心代码。

dictRehash

dictRehash有两个参数,d是rehash的dict指针,n是需要迁移到dictht[1]的非空桶数目;返回值0表示rehash完毕,否则返回1。

int dictRehash(dict *d, int n) {//rehash n个bucket到ht[1],或者扫了n*10次空bucket就退出
    int empty_visits = n*10; /* Max number of empty buckets to visit. *///最多只走empty_visits个空bucket,一旦遍历的空bucket数超过这个数则返回1,所以可能执行这个函数的时候一个bucket也没有rehash到ht[1]
    if (!dictIsRehashing(d)) return 0;//rehash已完成

    while(n-- && d->ht[0].used != 0) {//遍历n个bucket,ht[0]中还有dictEntry
        dictEntry *de, *nextde;

        /* Note that rehashidx can"t overflow as we are sure there are more
         * elements because ht[0].used != 0 */
        assert(d->ht[0].size > (unsigned long)d->rehashidx);
        while(d->ht[0].table[d->rehashidx] == NULL) {
            //当前bucket为空时跳到下一个bucket并且
            d->rehashidx++;
            if (--empty_visits == 0) return 1;
        }
        //直到当前bucket不为空bucket时
        de = d->ht[0].table[d->rehashidx];//当前bucket里第一个dictEntry的指针(地址)
        /* Move all the keys in this bucket from the old to the new hash HT */
        while(de) {//把当前bucket的所有ditcEntry节点都移到ht[1]
            unsigned int h;

            nextde = de->next;
            /* Get the index in the new hash table */
            h = dictHashKey(d, de->key) & d->ht[1].sizemask;//hash函数算出的值& 新hashtable(buckets)的sizemask,保证h会小于新buckets的size
            de->next = d->ht[1].table[h];//插入到链表的最前面!省时间
            d->ht[1].table[h] = de;

            d->ht[0].used--;//老dictht的used(节点数)-1
            d->ht[1].used++;//新dictht的used(节点数)+1
            de = nextde;
        }
        d->ht[0].table[d->rehashidx] = NULL;//当前bucket已经完全移走
        d->rehashidx++;//下一个bucket
    }

    /* Check if we already rehashed the whole table... */
    if (d->ht[0].used == 0) {
        zfree(d->ht[0].table);//释放掉ht[0].table的内存(buckets)
        d->ht[0] = d->ht[1];//浅复制,table只是一个地址,直接给ht[0]就好
        _dictReset(&d->ht[1]);//ht[1]的table置空
        d->rehashidx = -1;
        return 0;
    }

    /* More to rehash... */
    return 1;
}

拿上面的图作为的例子调用一次dictRehash(d, 1),会产生如下布局:

之前a和b的放在dictht[0]的同一个buckets索引[0]下,但是经过rehash,h = dictHashKey(d, de->key) & d->ht[1].sizemask,h可能依旧为0,也有可能变为4。ps:如果两个dictEntry仍然落在同一个索引下,它俩顺序会颠倒。

rehashidx+1

返回1 More to rehash

若在此基础上在执行一次dictRehash(d, 1),则会跳过索引为1的那个空bucket,迁移下一个bucket。

字典的基本操作 dictCreate:创建一个dict

有了rehash的基本认识,下面就可以说说redis字典支持的一些常规操作了:
redis用dictCreate创建并初始化一个dict,放源码一看就明白:

dict *dictCreate(dictType *type,
        void *privDataPtr)
{
    dict *d = zmalloc(sizeof(*d));

    _dictInit(d,type,privDataPtr);
    return d;
}

/* Initialize the hash table */
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;
}
static void _dictReset(dictht *ht)
{
    ht->table = NULL;
    ht->size = 0;
    ht->sizemask = 0;
    ht->used = 0;
}

需要注意的是创建初始化一个dict时并没有为buckets分配空间,table是赋值为null的。只有在往dict里添加dictEntry节点时才会为buckets分配空间,真正意义上创建一张hash表。
执行dictCreate后会得到如下布局:

dictAdd(增):添加一个dictEntry节点
int dictAdd(dict *d, void *key, void *val)//完整的添加dictEntry节点的流程
{
    dictEntry *entry = dictAddRaw(d,key);//只在buckets的某个索引里新建一个dictEntry并调整链表的位置,只设置key,不设置不设置val

    if (!entry) return DICT_ERR;
    dictSetVal(d, entry, val);//为这个entry设置值
    return DICT_OK;
}

//_dictKeyIndex会判断是否达到expand条件,若达到条件则执行dictExpand将dictht[1]扩大 并将改dict的rehash状态置为正在进行中(-1置为0)
dictEntry *dictAddRaw(dict *d, void *key)//new一个dictEntry然后把它放到某个buckets索引下的链表头部,填上key
{
    int index;
    dictEntry *entry;
    dictht *ht;

    if (dictIsRehashing(d)) _dictRehashStep(d);//如果正在rehash则被动rehash一步

    /* Get the index of the new element, or -1 if
     * the element already exists. */
    if ((index = _dictKeyIndex(d, key)) == -1)//计算这个key在当前dict应该放到bucket的哪个索引里,key已存在则返回-1
        return NULL;

    /* Allocate the memory and store the new entry.
     * Insert the element in top, with the assumption that in a database
     * system it is more likely that recently added entries are accessed
     * more frequently. */
    //虽然_dictKeyIndex()时已经确认过是哪张dictht,但是调用者没办法知道,所以再确认一下
    ht = dictIsRehashing(d) ? &d->ht[1] : &d->ht[0];//在rehash则把dictEntry加到ht[1]
    entry = zmalloc(sizeof(*entry));
    entry->next = ht->table[index];
    ht->table[index] = entry;
    ht->used++;

    /* Set the hash entry fields. */
    dictSetKey(d, entry, key);//如果dict d没有keyDup则直接entry->key = xxx,赋值
    return entry;
}

static int _dictKeyIndex(dict *d, const void *key)//根据dict和key返回这个key该存放的buckets的索引(但是用哪个dictht(ht[0]或ht[1])上层调用者是未知的),key已存在则返回-1
{
    unsigned int h, idx, table;
    dictEntry *he;

    /* Expand the hash table if needed */
    if (_dictExpandIfNeeded(d) == DICT_ERR)
        return -1;
    /* Compute the key hash value */
    h = dictHashKey(d, key);
    for (table = 0; table <= 1; table++) {
        idx = h & d->ht[table].sizemask;
        /* Search if this slot does not already contain the given key */
        he = d->ht[table].table[idx];//buckets 的idx索引下的第一个dictEntry的地址
        while(he) {//遍历一遍这个dictEntry链表
            if (key==he->key || dictCompareKeys(d, key, he->key))//如果key已经存在,返回-1
                return -1;
            he = he->next;
        }
        if (!dictIsRehashing(d)) break;//不在rehash时,直接跳出循环不做第二个dictht[1]的计算
    }
    return idx;
}

主要分为以下几个步骤:

1.根据key的hash值找到应该存放的位置(buckets索引)。

2.若dict是刚创建的还没有为bucekts分配内存,则会在找位置(_dictKeyIndex)时调用_dictExpandIfNeeded,为dictht[0]expand一个大小为4的buckets;若dict正好到了expand的时机,则会expand它的dictht[1],并将rehashidx置为0打开rehash开关,_dictKeyIndex返回的会是dictht[1]的索引。

3.申请一个dictEntry大小的内存插入到buckets对应索引下的链表头部,并给dictEntry设置next指针和key。

4.为dictEntry设置value

dictDelete(删):删除一个dictEntry节点

dict删除函数主要有三个,从低到高依次删除dictEntry、dictht、dict。

dictDelete在redis在字典里的作用是删除一个dictEntry并释放dictEntry成员key和成员v指向的内存;

_dictClear删除并释放一个dict的指定dictht;

dictRelease删除并释放整个dict。

//删除dictEntry并释放dictEntry成员key和成员v指向的内存
int dictDelete(dict *ht, const void *key) {
    return dictGenericDelete(ht,key,0);
}
static int dictGenericDelete(dict *d, const void *key, int nofree)//删除一个dictEntry节点,nofree参数指定是否释放这个节点的key和val的内存(如果key和val是指针的话),nofree为1不释放,0为释放
{
    unsigned int h, idx;
    dictEntry *he, *prevHe;
    int table;

    if (d->ht[0].size == 0) return DICT_ERR; /* d->ht[0].table is NULL */
    if (dictIsRehashing(d)) _dictRehashStep(d);//被动rehash一次
    h = dictHashKey(d, key);

    for (table = 0; table <= 1; table++) {
        idx = h & d->ht[table].sizemask;//找到key对应的bucket索引
        he = d->ht[table].table[idx];//索引的第一个dictEntry节点指针
        prevHe = NULL;
        while(he) {
            //单向链表删除步骤
            if (key==he->key || dictCompareKeys(d, key, he->key)) {//key匹配
                /* Unlink the element from the list */
                if (prevHe)
                    prevHe->next = he->next;
                else
                    d->ht[table].table[idx] = he->next;
                if (!nofree) {
                    dictFreeKey(d, he);
                    dictFreeVal(d, he);
                }
                zfree(he);
                d->ht[table].used--;
                return DICT_OK;
            }
            prevHe = he;
            he = he->next;
        }
        if (!dictIsRehashing(d)) break;//如果不在rehash,则不查第二个table(dictht[1])
    }
    return DICT_ERR; /* not found */
}

//删除一个dict的指定dictht,释放dictht的table内相关的全部内存,并reset dictht
int _dictClear(dict *d, dictht *ht, void(callback)(void *)) {//传递dict指针是为了调用dictType的相关函数,dictFreeVal里会调
    unsigned long i;

    /* Free all the elements */
    for (i = 0; i < ht->size && ht->used > 0; i++) {//buckets大小,dictEntry使用数
        dictEntry *he, *nextHe;

        if (callback && (i & 65535) == 0) callback(d->privdata);

        if ((he = ht->table[i]) == NULL) continue;
        while(he) {
            //遍历删除dictEntry链表
            nextHe = he->next;
            dictFreeKey(d, he);
            dictFreeVal(d, he);
            zfree(he);
            ht->used--;
            he = nextHe;
        }
    }
    /* Free the table and the allocated cache structure */
    zfree(ht->table);
    /* Re-initialize the table */
    _dictReset(ht);
    return DICT_OK; /* never fails */
}

//删除并释放整个dict
void dictRelease(dict *d)
{
    _dictClear(d,&d->ht[0],NULL);
    _dictClear(d,&d->ht[1],NULL);
    zfree(d);
}
dictReplace(改):修改一个dictEntry节点的成员v(值)
//修改一个dictEntry的val,也是一种添加dictEntry的方式,如果dictAdd失败(key已存在)则replace这个dictEntry的val
int dictReplace(dict *d, void *key, void *val)//用新val取代一个dictEntry节点的旧val
{
    dictEntry *entry, auxentry;

    /* Try to add the element. If the key
     * does not exists dictAdd will suceed. */
    if (dictAdd(d, key, val) == DICT_OK)//试着加一个新dictEntry,失败则说明key已存在
        return 1;
    /* It already exists, get the entry */
    entry = dictFind(d, key);//创建节点失败则一定能找到这个已经存在了的key
    /* Set the new value and free the old one. Note that it is important
     * to do that in this order, as the value may just be exactly the same
     * as the previous one. In this context, think to reference counting,
     * you want to increment (set), and then decrement (free), and not the
     * reverse. */
    auxentry = *entry;//需要替换val的dictEntry节点,auxentry用来删除(释放)val
    dictSetVal(d, entry, val);//替换val的操作
    dictFreeVal(d, &auxentry);//考虑val可能是一个指针,指针指向的内容不会被删除,所以调用这个dict的type类里的dictFreeVal释放掉那块内存
    return 0;
}

代码里还有一个dictReplaceRaw函数,这个函数跟replace没啥关系,只是封装了一下dictAddRaw,没有替换的功能。

dictFind(查):根据key找到当前dict存放该key的dictEntry
//返回dictEntry的地址
dictEntry *dictFind(dict *d, const void *key)//会执行被动rehash
{
    dictEntry *he;
    unsigned int h, idx, table;

    if (d->ht[0].used + d->ht[1].used == 0) return NULL; /* dict is empty */
    if (dictIsRehashing(d)) _dictRehashStep(d);//查找key的时候也会被动rehash
    h = dictHashKey(d, key);
    for (table = 0; table <= 1; table++) {
        idx = h & d->ht[table].sizemask;//先计算当前buckets中key应存放的索引
        he = d->ht[table].table[idx];//buckets 的idx索引下的第一个dictEntry的地
        while(he) {//遍历查找该链表
            if (key==he->key || dictCompareKeys(d, key, he->key))//如果key已经存在,返回-1
                return he;
            he = he->next;
        }
        if (!dictIsRehashing(d)) return NULL;//不在rehash时,直接跳出循环不在dictht[1]里查找
    }
    return NULL;
}
安全 非安全迭代器

介绍一下字典的迭代器
redis字典的迭代器分为两种,一种是safe迭代器另一种是unsafe迭代器:
safe迭代器在迭代的过程中用户可以对该dict进行CURD操作,unsafe迭代器在迭代过程中用户只能对该dict执行迭代操作。

上文说过每次执行CURD操作时,如果dict的rehash开关已经打开,则会执行一次被动rehash操作将dictht[0]的一个链表迁移到dictht[1]上。这时若迭代器进行迭代操作会导致重复迭代几个刚被rehash到dictht[1]的dictEntry节点。那么一边迭代一遍CRUD,这是怎么实现的呢?

redis在dict结构里增加一个iterator成员,用来表示绑定在当前dict上的safe迭代器数量,dict每次CRUD执行_dictRehashStep时判断一下是否有绑定safe迭代器,如果有则不进行rehash以免扰乱迭代器的迭代,这样safe迭代时字典就可以正常进行CRUD操作了。

static void _dictRehashStep(dict *d) {
    if (d->iterators == 0) dictRehash(d,1);
}

unsafe迭代器在执行迭代过程中不允许对dict进行其他操作,如何保证这一点呢?

redis在第一次执行迭代时会用dictht[0]、dictht[1]的used、size、buckets地址计算一个fingerprint(指纹),在迭代结束后释放迭代器时再计算一遍fingerprint看看是否与第一次计算的一致,若不一致则用断言终止进程,生成指纹的函数如下:

//unsafe迭代器在第一次dictNext时用dict的两个dictht的table、size、used进行hash算出一个结果
//最后释放iterator时再调用这个函数生成指纹,看看结果是否一致,不一致就报错.
//safe迭代器不会用到这个
long long dictFingerprint(dict *d) {
    long long integers[6], hash = 0;
    int j;

    integers[0] = (long) d->ht[0].table;//把指针类型转换成long
    integers[1] = d->ht[0].size;
    integers[2] = d->ht[0].used;
    integers[3] = (long) d->ht[1].table;
    integers[4] = d->ht[1].size;
    integers[5] = d->ht[1].used;

    /* We hash N integers by summing every successive integer with the integer
     * hashing of the previous sum. Basically:
     *
     * Result = hash(hash(hash(int1)+int2)+int3) ...
     *
     * This way the same set of integers in a different order will (likely) hash
     * to a different number. */
    for (j = 0; j < 6; j++) {
        hash += integers[j];
        /* For the hashing step we use Tomas Wang"s 64 bit integer hash. */
        hash = (~hash) + (hash << 21); // hash = (hash << 21) - hash - 1;
        hash = hash ^ (hash >> 24);
        hash = (hash + (hash << 3)) + (hash << 8); // hash * 265
        hash = hash ^ (hash >> 14);
        hash = (hash + (hash << 2)) + (hash << 4); // hash * 21
        hash = hash ^ (hash >> 28);
        hash = hash + (hash << 31);
    }
    return hash;
}

介绍完redis迭代器的两种类型,看看dictIterator的定义:

dictIterator定义
typedef struct dictIterator {
    dict *d;
    long index;//当前buckets索引,buckets索引类型是unsinged long,而这个初始化会是-1,所以long
    int table, safe;//table是ht的索引只有0和1,safe是安全迭代器和不安全迭代器
    //安全迭代器就等于加了一个锁在dict,使dict在CRUD时ditcEntry不能被动rehash
    dictEntry *entry, *nextEntry;//当前hash节点以及下一个hash节点
    /* unsafe iterator fingerprint for misuse detection. */
    long long fingerprint;//dict.c里的dictFingerprint(),不安全迭代器相关
} dictIterator;

接下来介绍迭代器相关函数

dictGetIterator:创建一个迭代器
//默认是new一个unsafe迭代器
dictIterator *dictGetIterator(dict *d)//获取一个iterator就是为这个dict new一个迭代器
{
    //不设置成员变量fingerprint,在dictNext的时候才设置。
    dictIterator *iter = zmalloc(sizeof(*iter));

    iter->d = d;
    iter->table = 0;
    iter->index = -1;
    iter->safe = 0;
    iter->entry = NULL;
    iter->nextEntry = NULL;
    return iter;
}

dictIterator *dictGetSafeIterator(dict *d) {
    dictIterator *i = dictGetIterator(d);

    i->safe = 1;
    return i;
}

为指定dict创建一个unsafe迭代器:dictGetIterator()
为指定dict创建一个safe迭代器:dictGetSafeIterator()
需要注意的是创建safe迭代器时并不会改变dict结构里iterator成员变量的计数,只有迭代真正发生的时候才会+1 表明该dict绑定了一个safe迭代器。

dictNext:迭代一个dictEntry节点
dictEntry *dictNext(dictIterator *iter)//如果下一个dictEntry不为空,则返回。为空则继续找下一个bucket的第一个dictEntry
{
    while (1) {
        if (iter->entry == NULL) {//新new的dictIterator的entry是null,或者到达一个bucket的链表尾部
            dictht *ht = &iter->d->ht[iter->table];//dictht的地址
            if (iter->index == -1 && iter->table == 0) {
                //刚new的dictIterator
                if (iter->safe)
                    iter->d->iterators++;
                else
                    iter->fingerprint = dictFingerprint(iter->d);//初始化unsafe迭代器的指纹,只进行一次
            }
            iter->index++;//buckets的下一个索引
            if (iter->index >= (long) ht->size) {
                //如果buckets的索引大于等于这个buckets的大小,则这个buckets迭代完毕
                
                if (dictIsRehashing(iter->d) && iter->table == 0) {//当前用的dictht[0]
                    //考虑rehash,换第二个dictht 
                    iter->table++;
                    iter->index = 0;//index复原成0,从第二个dictht的第0个bucket迭代
                    ht = &iter->d->ht[1];//设置这个是为了rehash时更新下面的iter->entry
                } else {
                    break;//迭代完毕了
                }
            }
            iter->entry = ht->table[iter->index];//更新entry为下一个bucket的第一个节点
        } else {
            iter->entry = iter->nextEntry;
        }
        if (iter->entry) {
            /* We need to save the "next" here, the iterator user
             * may delete the entry we are returning. */
            iter->nextEntry = iter->entry->next;
            return iter->entry;
        }
    }
    return NULL;
}

虽然safe迭代器会禁止rehash,但在迭代时有可能已经rehash了一部分,所以迭代器也会遍历在dictht[1]中的所有dictEntry。

dictScan

前面说的safe迭代器和unsafe迭代器都是建立在不能rehash的前提下。要通过这种迭代的方式遍历所有节点会停止该dict的被动rehash,阻止了rehash的正常进行。dictScan就是用来解决这种问题的,它可以在不停止rehash的前提下遍历到所有dictEntry节点,不过也有非常小的可能性返回重复的节点,具体如何做到的可能得另花大量篇幅介绍,有兴趣可以借助这篇博客理解。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/28128.html

相关文章

  • Redis3.2源码分析-字典dict

    摘要:里存放的是一堆工具函数的函数指针,保存中的某些函数需要作为参数的数据两个,平时用,时用当前到的哪个索引,时表示非状态安全迭代器的计数。迭代器的定义先不管,等下文讲到安全非安全迭代器的时候再细说。 最近工作有点忙,拖了好久才挤出时间学习dict源码。还是希望能坚持读下去。 先简单介绍一下redis字典 字典的目的是为了通过某个信息(key) 找到另一个信息(value)。为了快速从key...

    singerye 评论0 收藏0
  • Redis源码分析-压缩列表ziplist

    摘要:用不用作为分界是因为是的值,它用于判断是否到达尾部。这种类型的节点的大小介于与之间,但是为了表示整数,取出低四位之后会将其作为实际的值。当小于字节时,节点存为上图的第二种类型,高位为,后续位表示的长度。 // 文中引用的代码来源于Redis3.2 前言 Redis是基于内存的nosql,有些场景下为了节省内存redis会用时间换空间。ziplist就是很典型的例子。 介绍 ziplis...

    RyanQ 评论0 收藏0
  • Redis源码分析-压缩列表ziplist

    摘要:用不用作为分界是因为是的值,它用于判断是否到达尾部。这种类型的节点的大小介于与之间,但是为了表示整数,取出低四位之后会将其作为实际的值。当小于字节时,节点存为上图的第二种类型,高位为,后续位表示的长度。 // 文中引用的代码来源于Redis3.2 前言 Redis是基于内存的nosql,有些场景下为了节省内存redis会用时间换空间。ziplist就是很典型的例子。 介绍 ziplis...

    luckyw 评论0 收藏0
  • Redis3.2源码分析-整数集合intset

    摘要:是集合的底层实现之一,当存储整数集合并且数据量较小的情况下会使用作为的底层实现。当数据量较大或者集合元素为字符串时则会使用实现。快速复习字节序不论大端小端,内存中数据按照位字节分割。举个例子整数对应的进制表示是。 intset是Redis集合的底层实现之一,当存储整数集合并且数据量较小的情况下Redis会使用intset作为set的底层实现。当数据量较大或者集合元素为字符串时则会使用d...

    lemanli 评论0 收藏0
  • Redis3.2源码分析-整数集合intset

    摘要:是集合的底层实现之一,当存储整数集合并且数据量较小的情况下会使用作为的底层实现。当数据量较大或者集合元素为字符串时则会使用实现。快速复习字节序不论大端小端,内存中数据按照位字节分割。举个例子整数对应的进制表示是。 intset是Redis集合的底层实现之一,当存储整数集合并且数据量较小的情况下Redis会使用intset作为set的底层实现。当数据量较大或者集合元素为字符串时则会使用d...

    tunny 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<