您的位置:首页 > 数据库 > Redis

redis dict.c源码分析

2012-03-06 19:58 357 查看
写得比较简略,有错误的还请指出,有不懂的也可以留言讨论
/* Hash Tables Implementation.
*
* This file implements in memory hash tables with insert/del/replace/find/
* get-random-element operations. Hash tables will auto resize if needed
* tables of power of two in size are used, collisions are handled by
* chaining. See the source code for more information... :)
*/

#include "fmacros.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <assert.h>
#include <limits.h>
#include <sys/time.h>
#include <ctype.h>
#include "dict.h"
#include "zmalloc.h"

/* Using dictEnableResize() / dictDisableResize() we make possible to
* enable/disable resizing of the hash table as needed. This is very important
* for Redis, as we use copy-on-write and don't want to move too much memory
* around when there is a child performing saving operations.
*
* Note that even when dict_can_resize is set to 0, not all resizes are
* prevented: an hash table is still allowed to grow if the ratio between
* the number of elements and the buckets > dict_force_resize_ratio. */
static int dict_can_resize = 1;
static unsigned int dict_force_resize_ratio = 5;

/* -------------------------- private prototypes ---------------------------- */

static int _dictExpandIfNeeded(dict *ht);
static unsigned long _dictNextPower(unsigned long size);
static int _dictKeyIndex(dict *ht, const void *key);
static int _dictInit(dict *ht, dictType *type, void *privDataPtr);

/* -------------------------- hash functions -------------------------------- */

/* Thomas Wang's 32 bit Mix Function */
unsigned int dictIntHashFunction(unsigned int key)
{
key += ~(key << 15);
key ^=  (key >> 10);
key +=  (key << 3);
key ^=  (key >> 6);
key += ~(key << 11);
key ^=  (key >> 16);
return key;
}

/* Identity hash function for integer keys */
unsigned int dictIdentityHashFunction(unsigned int key)
{
return key;
}

/* Generic hash function (a popular one from Bernstein).
* A string hash into an integer
* I tested a few and this was the best. */
unsigned int dictGenHashFunction(const unsigned char *buf, int len) {
unsigned int hash = 5381;

while (len--)//++运算符优先级>*
hash = ((hash << 5) + hash) + (*buf++); /* hash * 33 + c */
return hash;
}

/* And a case insensitive version */
unsigned int dictGenCaseHashFunction(const unsigned char *buf, int len) {
unsigned int hash = 5381;

while (len--)
hash = ((hash << 5) + hash) + (tolower(*buf++)); /* hash * 33 + c */
return hash;
}

/* ----------------------------- API implementation ------------------------- */

/* Reset an hashtable already initialized with ht_init().
* NOTE: This function should only called by ht_destroy(). */
static void _dictReset(dictht *ht)
{
ht->table = NULL;
ht->size = 0;
ht->sizemask = 0;
ht->used = 0;
}

/* Create a new 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;
}

/* Resize the table to the minimal size that contains all the elements,
* but with the invariant of a USER/BUCKETS ratio near to <= 1 */
int dictResize(dict *d)
{
int minimal;

if (!dict_can_resize || dictIsRehashing(d)) return DICT_ERR;
minimal = d->ht[0].used;
if (minimal < DICT_HT_INITIAL_SIZE)
minimal = DICT_HT_INITIAL_SIZE;
return dictExpand(d, minimal);
}

/* Expand or create the hashtable */
int dictExpand(dict *d, unsigned long size)
{
dictht newht; /* the new hashtable */
unsigned long realsize = _dictNextPower(size);

/* the size is invalid if it is smaller than the number of
* elements already inside the hashtable */
if (dictIsRehashing(d) || d->ht[0].used > size)
return DICT_ERR;

/* Allocate the new hashtable and initialize all pointers to NULL */
newht.size = realsize;
newht.sizemask = realsize - 1;
newht.table = zcalloc(realsize * sizeof(dictEntry*));
newht.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) {
d->ht[0] = newht;
return DICT_OK;
}

/* Prepare a second hash table for incremental rehashing */
d->ht[1] = newht;
d->rehashidx = 0;//
return DICT_OK;
}

/* Performs N steps of incremental rehashing. Returns 1 if there are still
* keys to move from the old to the new hash table, otherwise 0 is returned.
* Note that a rehashing step consists in moving a bucket (that may have more
* than one key as we use chaining) from the old to the new hash table.
* rehash是在hash table的大小不能满足需求,造成过多hash碰撞后需要进行的扩容hash table的操作,
* 其实通常的做法确实是建立一个额外的hash table,将原来的hash table中的数据在新的数据中进行重新
* 输入,从而生成新的hash表。*/
int dictRehash(dict *d, int n) {
if (!dictIsRehashing(d)) return 0;

while(n--) {
dictEntry *de, *nextde;
//将该key按ht[1]的 桶的大小重新rehash,并在rehash完后将ht[0]指向ht[1],然后将ht[1]清空
/* Check if we already rehashed the whole table... */
if (d->ht[0].used == 0) {
zfree(d->ht[0].table);
d->ht[0] = d->ht[1];
_dictReset(&d->ht[1]);
d->rehashidx = -1;
return 0;
}

/* Note that rehashidx can't overflow as we are sure there are more
* elements because ht[0].used != 0 */
while(d->ht[0].table[d->rehashidx] == NULL) d->rehashidx++;
de = d->ht[0].table[d->rehashidx];
/* Move all the keys in this bucket from the old to the new hash HT */
while(de) {
unsigned int h;

nextde = de->next;
/* Get the index in the new hash table */
h = dictHashKey(d, de->key) & d->ht[1].sizemask;
de->next = d->ht[1].table[h];
d->ht[1].table[h] = de;//add to the head of a list
d->ht[0].used--;
d->ht[1].used++;
de = nextde;
}

d->ht[0].table[d->rehashidx] = NULL;
d->rehashidx++;
}
return 1;
}

long long timeInMilliseconds(void) {
struct timeval tv;

gettimeofday(&tv,NULL);
return (((long long)tv.tv_sec)*1000)+(tv.tv_usec/1000);
}

/* Rehash for an amount of time between ms milliseconds and ms + 1 milliseconds
* 1ms rehash 100个bucket, 在serverCron中执行*/
int dictRehashMilliseconds(dict *d, int ms) {
long long start = timeInMilliseconds();
int rehashes = 0;

while(dictRehash(d,100)) {
rehashes += 100;
if (timeInMilliseconds() - start > ms) break;
}
return rehashes;
}

/* This function performs just a step of rehashing, and only if there are
* no safe iterators bound to our hash table. When we have iterators in the
* middle of a rehashing we can't mess with the two hash tables otherwise
* some element can be missed or duplicated.
* This function is called by common lookup or update operations in the
* dictionary so that the hash table automatically migrates from H1 to H2
* while it is actively used.
* 由于_dictRehashStep是被dictGetRandomKey、dictFind、 dictGenericDelete、dictAdd
* 调用的,因此在每次dict增删查改时都会被调用,这无疑就加快了rehash过程*/
static void _dictRehashStep(dict *d) {
if (d->iterators == 0) dictRehash(d,1);
}

/* Add an element to the target hash table */
int dictAdd(dict *d, void *key, void *val)
{
int index;
dictEntry *entry;
dictht *ht;

if (dictIsRehashing(d)) _dictRehashStep(d);//懒惰rehash

/* Get the index of the new element, or -1 if
* the element already exists. */
if ((index = _dictKeyIndex(d, key)) == -1)
return DICT_ERR;

/* Allocates the memory and stores key */
ht = dictIsRehashing(d) ? &d->ht[1] : &d->ht[0];
entry = zmalloc(sizeof(*entry));
entry->next = ht->table[index];
ht->table[index] = entry;//insert into the list head
ht->used++;

/* Set the hash entry fields. */
dictSetHashKey(d, entry, key);
dictSetHashVal(d, entry, val);
return DICT_OK;
}

/* Add an element, discarding the old if the key already exists.
* Return 1 if the key was added from scratch, 0 if there was already an
* element with such key and dictReplace() just performed a value update
* operation. */
int dictReplace(dict *d, void *key, void *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)
return 1;
/* It already exists, get the entry */
entry = dictFind(d, key);
/* Free the old value and set the new one */
/* 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, thanks to reference counting,
* you want to increment (set), and then decrement (free), and not the
* reverse. */
auxentry = *entry;
dictSetHashVal(d, entry, val);
dictFreeEntryVal(d, &auxentry);
return 0;
}

/* Search and remove an element */
static int dictGenericDelete(dict *d, const void *key, int nofree)
{
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);
h = dictHashKey(d, key);

for (table = 0; table <= 1; table++) {
idx = h & d->ht.sizemask;
he = d->ht
.table[idx]; prevHe = NULL; while(he) { if (dictCompareHashKeys(d, key, he->key)) { /* Unlink the element from the list */ if (prevHe) prevHe->next = he->next; else d->ht
.table[idx] = he->next; if (!nofree) { dictFreeEntryKey(d, he); dictFreeEntryVal(d, he); } zfree(he); d->ht
.used--; return DICT_OK; } prevHe = he; he = he->next; } if (!dictIsRehashing(d)) break; } return DICT_ERR; /* not found */ } int dictDelete(dict *ht, const void *key) { return dictGenericDelete(ht,key,0); } int dictDeleteNoFree(dict *ht, const void *key) { return dictGenericDelete(ht,key,1); } /* Destroy an entire dictionary */ int _dictClear(dict *d, dictht *ht) { unsigned long i; /* Free all the elements */ for (i = 0; i < ht->size && ht->used > 0; i++) { dictEntry *he, *nextHe; if ((he = ht->table[i]) == NULL) continue; while(he) { nextHe = he->next; dictFreeEntryKey(d, he); dictFreeEntryVal(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 */ } /* Clear & Release the hash table */ void dictRelease(dict *d) { _dictClear(d,&d->ht[0]); _dictClear(d,&d->ht[1]); zfree(d); } dictEntry *dictFind(dict *d, const void *key) { dictEntry *he; unsigned int h, idx, table; if (d->ht[0].size == 0) return NULL; /* We don't have a table at all */ if (dictIsRehashing(d)) _dictRehashStep(d); h = dictHashKey(d, key); for (table = 0; table <= 1; table++) { idx = h & d->ht
.sizemask; he = d->ht
.table[idx]; while(he) { if (dictCompareHashKeys(d, key, he->key)) return he; he = he->next; } if (!dictIsRehashing(d)) return NULL; } return NULL; } void *dictFetchValue(dict *d, const void *key) { dictEntry *he; he = dictFind(d,key); return he ? dictGetEntryVal(he) : NULL; } dictIterator *dictGetIterator(dict *d) { 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; } /* * redis的dict提供了一个迭代器。由于rehash的存在,如果不加保护,某写数据可能会被返回两次。比如,一个数据 * e在ht[0]中,此时还没有对e所在的桶进行rehash,迭代器访问完e之后,恰好对e所在的桶进行了rehash。那么,当 * 迭代器遍历ht[1]中的时候,e会被再次返回。为了防止这种现象,redis限制一旦有迭代器对dict进行访问,那么rehash * 就会暂停,直到不再有迭代器访问字典。结构体dict中的iterators用于记录当前正在访问字典的迭代器。可以有多个迭代器 * 同时访问字典。迭代器返回的数据可以被删除。迭代器通过记录数据的指针和其在链表中的后继数据的指针实现对删除的支持。 redis限制有迭代器访问的时候禁止rehash,但是,在rehash的过程中迭代器可以随时对字典进行遍历。一旦有迭代器遍历字典, rehash就会暂停直到遍历结束。迭代器也会根据当前是否在进行rehahs来判断是否需要访问ht[1]。 返回iter->entry作为当前entry */ dictEntry *dictNext(dictIterator *iter) { while (1) { if (iter->entry == NULL) { dictht *ht = &iter->d->ht[iter->table]; if (iter->safe && iter->index == -1 && iter->table == 0) iter->d->iterators++;//number of iterators currently running iter->index++; if (iter->index >= (signed) ht->size) { if (dictIsRehashing(iter->d) && iter->table == 0) { iter->table++; iter->index = 0; ht = &iter->d->ht[1]; } else { break; } } iter->entry = ht->table[iter->index]; } 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; } void dictReleaseIterator(dictIterator *iter) { if (iter->safe && !(iter->index == -1 && iter->table == 0)) iter->d->iterators--; zfree(iter); } /* Return a random entry from the hash table. Useful to * implement randomized algorithms * 先随机返回一个dictEntry的头,然后随机返回chaining中的一个Entry */ dictEntry *dictGetRandomKey(dict *d) { dictEntry *he, *orighe; unsigned int h; int listlen, listele; if (dictSize(d) == 0) return NULL; if (dictIsRehashing(d)) _dictRehashStep(d); if (dictIsRehashing(d)) { do { h = random() % (d->ht[0].size + d->ht[1].size); he = (h >= d->ht[0].size) ? d->ht[1].table[h - d->ht[0].size] : d->ht[0].table[h]; } while(he == NULL); } else { do { h = random() & d->ht[0].sizemask; he = d->ht[0].table[h]; } while(he == NULL); } /* Now we found a non empty bucket, but it is a linked * list and we need to get a random element from the list. * The only sane way to do so is counting the elements and * select a random index. */ listlen = 0; orighe = he; while(he) { he = he->next; listlen++; } listele = random() % listlen; he = orighe; while(listele--) he = he->next; return he; } /* ------------------------- private functions ------------------------------ */ /* Expand the hash table if needed */ 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 intial size. */ 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)) { return dictExpand(d, ( (d->ht[0].size > d->ht[0].used) ? d->ht[0].size : d->ht[0].used) * 2); } return DICT_OK; } /* Our hash table capability is a power of two * 返回一个数(DICT_HT_INITIAL_SIZE * 2 ^ x)(x是自然数)使之恰好比size大 */ static unsigned long _dictNextPower(unsigned long size) { unsigned long i = DICT_HT_INITIAL_SIZE; if (size >= LONG_MAX) return LONG_MAX;//unsigned long and long range is not equal while(1) { if (i >= size) return i; i *= 2; } } /* Returns the index of a free slot that can be populated with * an hash entry for the given 'key'. * If the key already exists, -1 is returned. * * Note that if we are in the process of rehashing the hash table, the * index is always returned in the context of the second (new) hash table. */ static int _dictKeyIndex(dict *d, const void *key) { unsigned int h, idx, table; dictEntry *he; /* Expand the hashtable 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
.sizemask; /* Search if this slot does not already contain the given key */ he = d->ht
.table[idx]; while(he) { if (dictCompareHashKeys(d, key, he->key)) return -1; he = he->next; } if (!dictIsRehashing(d)) break; } return idx; } void dictEmpty(dict *d) { _dictClear(d,&d->ht[0]); _dictClear(d,&d->ht[1]); d->rehashidx = -1; d->iterators = 0; } #define DICT_STATS_VECTLEN 50 static void _dictPrintStatsHt(dictht *ht) { unsigned long i, slots = 0, chainlen, maxchainlen = 0; unsigned long totchainlen = 0; unsigned long clvector[DICT_STATS_VECTLEN]; if (ht->used == 0) { printf("No stats available for empty dictionaries\n"); return; } for (i = 0; i < DICT_STATS_VECTLEN; i++) clvector[i] = 0; for (i = 0; i < ht->size; i++) { dictEntry *he; if (ht->table[i] == NULL) { clvector[0]++; continue; } slots++;//slots是非空bucket桶数目 /* For each hash entry on this slot... */ chainlen = 0; he = ht->table[i]; while(he) { chainlen++; he = he->next; } //i映射到clvector[i]表示桶中有i个元素的桶的数目为clvector[i], //超过DICT_STATS_VECTLEN则全部计入最后一个元素中 clvector[(chainlen < DICT_STATS_VECTLEN) ? chainlen : (DICT_STATS_VECTLEN-1)]++; if (chainlen > maxchainlen) maxchainlen = chainlen; totchainlen += chainlen; } printf("Hash table stats:\n"); printf(" table size: %ld\n", ht->size); printf(" number of elements: %ld\n", ht->used); printf(" different slots: %ld\n", slots); printf(" max chain length: %ld\n", maxchainlen); printf(" avg chain length (counted): %.02f\n", (float)totchainlen/slots); printf(" avg chain length (computed): %.02f\n", (float)ht->used/slots); printf(" Chain length distribution:\n"); for (i = 0; i < DICT_STATS_VECTLEN-1; i++) { if (clvector[i] == 0) continue; printf(" %s%ld: %ld (%.02f%%)\n",(i == DICT_STATS_VECTLEN-1)?">= ":"", i, clvector[i], ((float)clvector[i]/ht->size)*100); } } void dictPrintStats(dict *d) { _dictPrintStatsHt(&d->ht[0]); if (dictIsRehashing(d)) { printf("-- Rehashing into ht[1]:\n"); _dictPrintStatsHt(&d->ht[1]); } } void dictEnableResize(void) { dict_can_resize = 1; } void dictDisableResize(void) { dict_can_resize = 0; } #if 0 /* The following are just example hash table types implementations. * Not useful for Redis so they are commented out. */ /* ----------------------- StringCopy Hash Table Type ------------------------*/ static unsigned int _dictStringCopyHTHashFunction(const void *key) { return dictGenHashFunction(key, strlen(key)); } static void *_dictStringDup(void *privdata, const void *key) { int len = strlen(key); char *copy = zmalloc(len+1); DICT_NOTUSED(privdata); memcpy(copy, key, len); copy[len] = '\0'; return copy; } static int _dictStringCopyHTKeyCompare(void *privdata, const void *key1, const void *key2) { DICT_NOTUSED(privdata); return strcmp(key1, key2) == 0; } static void _dictStringDestructor(void *privdata, void *key) { DICT_NOTUSED(privdata); zfree(key); } dictType dictTypeHeapStringCopyKey = { _dictStringCopyHTHashFunction, /* hash function */ _dictStringDup, /* key dup */ NULL, /* val dup */ _dictStringCopyHTKeyCompare, /* key compare */ _dictStringDestructor, /* key destructor */ NULL /* val destructor */ }; /* This is like StringCopy but does not auto-duplicate the key. * It's used for intepreter's shared strings. */ dictType dictTypeHeapStrings = { _dictStringCopyHTHashFunction, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ _dictStringCopyHTKeyCompare, /* key compare */ _dictStringDestructor, /* key destructor */ NULL /* val destructor */ }; /* This is like StringCopy but also automatically handle dynamic * allocated C strings as values. */ dictType dictTypeHeapStringCopyKeyValue = { _dictStringCopyHTHashFunction, /* hash function */ _dictStringDup, /* key dup */ _dictStringDup, /* val dup */ _dictStringCopyHTKeyCompare, /* key compare */ _dictStringDestructor, /* key destructor */ _dictStringDestructor, /* val destructor */ }; #endif
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: