memcached源碼分析-----LRU隊列與item結構體,memcached-----lru

來源:互聯網
上載者:User

memcached源碼分析-----LRU隊列與item結構體,memcached-----lru


        轉載請註明出處:http://blog.csdn.net/luotuo44/article/details/42869325



LRU隊列:

        之前的《slab記憶體配置》博文已經說到一個slab class裡面的所有slab分配器都只分配相同大小的item,不同的slab class分配不同大小的item。item結構體裡面有一個slabs_clsid成員,用來指明自己是屬於哪個slab class的。這裡把slabs_clsid值相同的item稱為是同一類item。

        slab分配器負責分配一個item,但這個item並非直接給雜湊表進行管理。從《雜湊表的刪除操作》可以看到,對雜湊表中的某一個item進行刪除只是簡單地將這個item從雜湊表的衝突鏈中刪除掉,並沒有把item記憶體歸還給slab。實際上,slab分配器分配出去的item是由一個LRU隊列進行管理的。當一個item從LRU隊列中刪除就會歸還給slab分配器 。


        LRU隊列其實是一個雙向鏈表。memcached裡面有多條LRU隊列,條數等於item的種類數。所以呢,同一類item(slabs_clsid成員變數值相等)將放到同一條LRU隊列中。之所以是雙向鏈表,是因為要方便從前後兩個方向插入和遍曆鏈表。下面看一下item結構體的部分成員。

typedef struct _stritem {    struct _stritem *next; //next指標,用於LRU鏈表    struct _stritem *prev; //prev指標,用於LRU鏈表    struct _stritem *h_next;//h_next指標,用於雜湊表的衝突鏈    rel_time_t      time;   //最後一次訪問時間。絕對時間  ...    uint8_t         slabs_clsid;/* which slab class we're in */} item;

        接下來看一下管理LRU隊列的資料結構。其實是超級簡單的,就三個全域數組而已,而且是static數組(開心吧)。

//memcached.h檔案#define POWER_LARGEST  200//items.c檔案#define LARGEST_ID POWER_LARGESTstatic item *heads[LARGEST_ID];//指向每一個LRU隊列頭static item *tails[LARGEST_ID];//指向每一個LRU隊列尾static unsigned int sizes[LARGEST_ID];//每一個LRU隊列有多少個item

        可以看到這三個數組的大小是和slabclass提供的最大slab class個數是一樣的。這樣也印證了一個LRU隊列就對應一類item。heads[i]指向第i類LRU鏈表的第一個item,tails[i]則指向了第i類LRU鏈表的最後一個item,sizes[i]則指明第i類LRU鏈表有多少個item。由LRU隊列和heads和tails構成的結構如所示:

        



LRU隊列的基本操作:


插入操作:

        假設我們有一個item要插入到LRU鏈表中,那麼可以通過調用item_link_q函數把item插入到LRU隊列中。下面是具體的實現代碼。

//將item插入到LRU隊列的頭部static void item_link_q(item *it) { /* item is the new head */    item **head, **tail;    assert(it->slabs_clsid < LARGEST_ID);    assert((it->it_flags & ITEM_SLABBED) == 0);    head = &heads[it->slabs_clsid];    tail = &tails[it->slabs_clsid];    assert(it != *head);    assert((*head && *tail) || (*head == 0 && *tail == 0));//頭插法插入該item    it->prev = 0;    it->next = *head;    if (it->next) it->next->prev = it;    *head = it;//該item作為對應鏈表的第一個節點//如果該item是對應id上的第一個item,那麼還會被認為是該id鏈上的最後一個item//因為在head那裡使用頭插法,所以第一個插入的item,到了後面確實成了最後一個item    if (*tail == 0) *tail = it;    sizes[it->slabs_clsid]++;//個數加一    return;}

刪除操作:

        有了插入函數,肯定有對應的刪除函數。刪除函數是蠻簡單,主要是處理刪除這個節點後,該節點的前後驅節點怎麼拼接在一起。

//將it從對應的LRU隊列中刪除static void item_unlink_q(item *it) {    item **head, **tail;    assert(it->slabs_clsid < LARGEST_ID);    head = &heads[it->slabs_clsid];    tail = &tails[it->slabs_clsid];    if (*head == it) {//鏈表上的第一個節點        assert(it->prev == 0);        *head = it->next;    }    if (*tail == it) {//鏈表上的最後一個節點        assert(it->next == 0);        *tail = it->prev;    }    assert(it->next != it);    assert(it->prev != it);//把item的前驅節點和後驅節點串連起來    if (it->next) it->next->prev = it->prev;    if (it->prev) it->prev->next = it->next;    sizes[it->slabs_clsid]--;//個數減一    return;}

        可以看到無論是插入還是刪除一個item,其耗時都是常數。其實對於memcached來說幾乎所有的操作時間複雜度都是常數級的。


更新操作:

        為什麼要把item插入到LRU隊列頭部呢?當然實現簡單是其中一個原因。但更重要的是這是一個LRU隊列!!還記得作業系統裡面的LRU吧。這是一種淘汰機制。在LRU隊列中,排得越靠後就認為是越少使用的item,此時被淘汰的幾率就越大。所以新鮮item(訪問時間新),要排在不那麼新鮮item的前面,所以插入LRU隊列的頭部是不二選擇。下面的do_item_update函數佐證了這一點。do_item_update函數是先把舊的item從LRU隊列中刪除,然後再插入到LRU隊列中(此時它在LRU隊列中排得最前)。除了更新item在隊列中的位置外,還會更新item的time成員,該成員指明上一次訪問的時間(絕對時間)。如果不是為了LRU,那麼do_item_update函數最簡單的實現就是直接更新time成員即可。

#define ITEM_UPDATE_INTERVAL 60 //更新頻率為60秒void do_item_update(item *it) {//下面的代碼可以看到update操作是耗時的。如果這個item頻繁被訪問,//那麼會導致過多的update,過多的一系列費時操作。此時更新間隔就應運而生//了。如果上一次的訪問時間(也可以說是update時間)距離現在(current_time)//還在更新間隔內的,就不更新。超出了才更新。    if (it->time < current_time - ITEM_UPDATE_INTERVAL) {        mutex_lock(&cache_lock);        if ((it->it_flags & ITEM_LINKED) != 0) {            item_unlink_q(it);//從LRU隊列中刪除            it->time = current_time;//更新訪問時間            item_link_q(it);//插入到LRU隊列的頭部        }        mutex_unlock(&cache_lock);    }}

        memcached處理get命令時會調用do_item_update函數更新item的訪問時間,更新其在LRU隊列的位置。在memcached中get命令是很頻繁的命令,排在LRU隊列第一或者前幾的item更是頻繁被get。對於排在前幾名的item來說,調用do_item_update是意義不大的,因為調用do_item_update後其位置還是前幾名,並且LRU淘汰再多item也難於淘汰不到它們(一個LRU隊列的item數量是很多的)。另一方面,do_item_update函數耗時還是會有一定的耗時,因為要搶佔cache_lock鎖。如果頻繁調用do_item_update函數效能將下降很多。於是memcached就是使用了更新間隔。



        前面講了怎麼在LRU隊列中插入和刪除一個item,現在講一下怎麼從slab分配器中申請一個item和怎麼歸還item給slab分配器。


item結構體:

        雖然前面多次提到了item,但item長成什麼樣子估計讀者還是迷迷糊糊的。下面看一下item結構體的完整定義吧,留意英文注釋。

#define ITEM_LINKED 1 //該item插入到LRU隊列了#define ITEM_CAS 2 //該item使用CAS#define ITEM_SLABBED 4 //該item還在slab的空閑隊列裡面,沒有分配出去#define ITEM_FETCHED 8 //該item插入到LRU隊列後,被worker線程訪問過typedef struct _stritem {    struct _stritem *next;//next指標,用於LRU鏈表    struct _stritem *prev;//prev指標,用於LRU鏈表    struct _stritem *h_next;//h_next指標,用於雜湊表的衝突鏈    rel_time_t      time;//最後一次訪問時間。絕對時間    rel_time_t      exptime;//到期失效時間,絕對時間    int             nbytes;//本item存放的資料的長度       unsigned short  refcount;//本item的引用數    uint8_t         nsuffix;//尾碼長度    /* length of flags-and-length string */    uint8_t         it_flags;//item的屬性   /* ITEM_* above */    uint8_t         slabs_clsid;/* which slab class we're in */    uint8_t         nkey;//索引值的長度       /* key length, w/terminating null and padding */    /* this odd type prevents type-punning issues when we do     * the little shuffle to save space when not using CAS. */    union {        uint64_t cas;        char end;    } data[];    /* if it_flags & ITEM_CAS we have 8 bytes CAS */    /* then null-terminated key */    /* then " flags length\r\n" (no terminating null) */    /* then data with terminating \r\n (no terminating null; it's binary!) */} item;

        上面代碼裡面的英文注釋說明了item布局。item結構體的最後一個成員是data[],這樣的定義稱為柔性數組。柔性數組的一個使用特點是,資料域就存放在數組的後面。memcached的item也是這樣使用柔性數組的。上面的item只是定義了item結構體本身的成員,但之前的博文一直用item表示item儲存的資料。這樣寫是合理的。因為item結構體本身和item對應的資料都是存放slab分配器分配的同一塊記憶體裡面。在《slab記憶體 Clerk》初始化slabclass數組的時候,其分配的記憶體塊大小是sizeof(item) +settings.chunk_size。


        item結構體後面緊接著的是一堆資料,並非僅僅是使用者要儲存的data,具體如所示:

        


        看上面的圖可能還不完全清楚明了item以及對應資料的儲存形式。我懂的,碼農是需要代碼才能完全清楚明了的。

#define ITEM_key(item) (((char*)&((item)->data)) \         + (((item)->it_flags & ITEM_CAS) ? sizeof(uint64_t) : 0))#define ITEM_suffix(item) ((char*) &((item)->data) + (item)->nkey + 1 \         + (((item)->it_flags & ITEM_CAS) ? sizeof(uint64_t) : 0))#define ITEM_data(item) ((char*) &((item)->data) + (item)->nkey + 1 \         + (item)->nsuffix \         + (((item)->it_flags & ITEM_CAS) ? sizeof(uint64_t) : 0))#define ITEM_ntotal(item) (sizeof(struct _stritem) + (item)->nkey + 1 \         + (item)->nsuffix + (item)->nbytes \         + (((item)->it_flags & ITEM_CAS) ? sizeof(uint64_t) : 0))static size_t item_make_header(const uint8_t nkey, const int flags, const int nbytes,                     char *suffix, uint8_t *nsuffix) {    /* suffix is defined at 40 chars elsewhere.. */    *nsuffix = (uint8_t) snprintf(suffix, 40, " %d %d\r\n", flags, nbytes - 2);    return sizeof(item) + nkey + *nsuffix + nbytes;//計算總大小}//key、flags、exptime三個參數是使用者在使用set、add命令儲存一條資料時輸入的參數。//nkey是key字串的長度。nbytes則是使用者要儲存的data長度+2,因為在data的結尾處還要加上"\r\n"//cur_hv則是根據索引值key計算得到的雜湊值。item *do_item_alloc(char *key, const size_t nkey, const int flags,                    const rel_time_t exptime, const int nbytes,                    const uint32_t cur_hv) {    uint8_t nsuffix;    item *it = NULL;    char suffix[40];//要儲存這個item需要的總空間。要注意第一個參數是nkey+1,所以上面的那些宏計算時//使用了(item)->nkey + 1    size_t ntotal = item_make_header(nkey + 1, flags, nbytes, suffix, &nsuffix);    if (settings.use_cas) {//開啟了CAS功能        ntotal += sizeof(uint64_t);    }//根據大小判斷從屬於哪個slab    unsigned int id = slabs_clsid(ntotal);    if (id == 0)//0表示不屬於任何一個slab        return 0;...it = slabs_alloc(ntotal, id);//從slab分配器中申請記憶體it->refcount = 1;it->it_flags = settings.use_cas ? ITEM_CAS : 0;    it->nkey = nkey;    it->nbytes = nbytes;    memcpy(ITEM_key(it), key, nkey);//這裡只拷貝nkey個位元組,最後一個位元組空著    it->exptime = exptime;    memcpy(ITEM_suffix(it), suffix, (size_t)nsuffix);    it->nsuffix = nsuffix;return it;}

        碼農們好好體會上面代碼中的那個幾個宏定義以及item_make_header函數。上面的代碼還是超級簡單地介紹了do_item_alloc函數,之所以說超級簡單是因為這個函數實際上是相當複雜的。

 


        上面簡單給出了向slab申請一個item,現在貼出歸還item的代碼。

//items.c檔案void item_free(item *it) {    size_t ntotal = ITEM_ntotal(it);    unsigned int clsid;    clsid = it->slabs_clsid;    it->slabs_clsid = 0;    slabs_free(it, ntotal, clsid);}//slabs.c檔案void slabs_free(void *ptr, size_t size, unsigned int id) {    pthread_mutex_lock(&slabs_lock);    do_slabs_free(ptr, size, id);//歸還給slab分配器    pthread_mutex_unlock(&slabs_lock);}


item和雜湊表的聯絡:

        前面的do_item_alloc函數是根據所需的大小申請一個item。從do_item_alloc實現代碼來看,它沒有把這個item插入到雜湊表和LRU隊列中。實際上這個任務是由另外的函數實現的。

        接下來看一下,怎麼把item傳給雜湊表、LRU隊列以及怎麼從雜湊表、LRU隊列收回item(有時還需要歸還給slab的)。

//將item插入到雜湊表和LRU隊列中,插入到雜湊表需要雜湊值hvint do_item_link(item *it, const uint32_t hv) {//確保這個item已經從slab分配出去並且還沒插入到LRU隊列中    assert((it->it_flags & (ITEM_LINKED|ITEM_SLABBED)) == 0);//當雜湊表不在為擴充而遷移資料時,就往雜湊表插入item//當雜湊表在遷移資料時,會佔有這個鎖。    mutex_lock(&cache_lock);    it->it_flags |= ITEM_LINKED;//加入 已link標誌    it->time = current_time;    /* Allocate a new CAS ID on link. */    ITEM_set_cas(it, (settings.use_cas) ? get_cas_id() : 0);    assoc_insert(it, hv);//將這個item插入到雜湊表中    item_link_q(it);//將這個item插入到鏈表中    refcount_incr(&it->refcount);//引用計數加一    mutex_unlock(&cache_lock);    return 1;}//從雜湊表刪除,所以需要雜湊值hvvoid do_item_unlink(item *it, const uint32_t hv) {    mutex_lock(&cache_lock);    if ((it->it_flags & ITEM_LINKED) != 0) {        it->it_flags &= ~ITEM_LINKED;//減去已link標誌        assoc_delete(ITEM_key(it), it->nkey, hv);//將這個item從雜湊表中刪除        item_unlink_q(it);//從鏈表中刪除該item        do_item_remove(it);//向slab歸還這個item    }    mutex_unlock(&cache_lock);}void do_item_remove(item *it) {    assert((it->it_flags & ITEM_SLABBED) == 0);    assert(it->refcount > 0);    if (refcount_decr(&it->refcount) == 0) {//引用計數等於0的時候歸還        item_free(it);//歸還該item給slab    }}

        在使用do_item_remove函數向slab歸還item時,會先測試這個item的引用數是否等於0。引用數可以簡單理解為有沒有worker線程在使用這個item。引用數的將會在後面的博文中詳細講解。



        前面的代碼中很少看到鎖。但實際上前面的item操作都是需要加鎖的,因為可能多個worker線程同時操作雜湊表和LRU隊列。之所以很少看到鎖是因為他們都使用了包裹函數(如果看過《UNIX網路編程》,這個概念應該不陌生)。在包裹函數中加鎖和解鎖。前面的函數中,函數名一般都是以do_作為首碼。其對應的包裹函數名就是去掉首碼do_。鎖的介紹不是本博文的任務,後面會有專門的博文介紹鎖的使用。





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.