1. 程式人生 > >redis源碼分析(3)-- 基本數據結構字典dict

redis源碼分析(3)-- 基本數據結構字典dict

下一個 edi code int current tty 大小 .com 個數

一、字典結構

Redis中字典采用hash表結構,如下:

typedef struct dictht {
    dictEntry **table; // hash表數組
    unsigned long size; // hash表大小
    unsigned long sizemask; // 掩碼
    unsigned long used; // 已經使用的大小
} dictht;

table是一個數組,每個元素指向一個dictEntry結構。size表示hash表大小,used表示使用的大小。一個size=4的空hash表如下:

技術分享

dictEntry是一個key-value pair, 定義為:

 1 typedef struct dictEntry {
 2     void *key; // key
 3     union { 
 4         void *val;
 5         uint64_t u64;
 6         int64_t s64;
 7         double d;
 8     } v; // value
 9     struct dictEntry *next; // 指向下一個key-value
10 } dictEntry;

next指針用於解決hash沖突,redis總采用直接鏈址法解決沖突。舉例:

技術分享

Redis中字典定義:

typedef struct
dict { dictType *type; // type和privdata區別操作不同類型key-value void *privdata; dictht ht[2]; long rehashidx; /* rehashing not in progress if rehashidx == -1 */ int iterators; /* number of iterators currently running */ } dict;

ht[2]中一般只有ht[0]使用,ht[1]在rehash時使用,ht[1]和rehashindex使用後續介紹。

技術分享

redis源碼分析(3)-- 基本數據結構字典dict