簡單的寫寫,看完了memcached的這部分代碼之后覺得跟我的ccache還是很像的.
1) 分配
memcached中的內存全部由類型為slabclass_t的結構體保存
typedef struct {
unsigned int size; /* sizes of items */
unsigned int perslab; /* how many items per slab */
void **slots; /* list of item ptrs */
unsigned int sl_total; /* size of previous array */
unsigned int sl_curr; /* first free slot */
void *end_page_ptr; /* pointer to next free item at end of page, or 0 */
unsigned int end_page_free; /* number of items remaining at end of last alloced page */
unsigned int slabs; /* how many slabs were allocated for this class */
void **slab_list; /* array of slab pointers */
unsigned int list_size; /* size of prev array */
unsigned int killing; /* index+1 of dying slab, or zero if none */
} slabclass_t;
有一個全局的slabclass_t的數組,slabclass_t中的size字段保存每個slab所能保存的數據大小.在這個slabclass_t數組中,size字段都是遞增的,遞增的因子由slabs_init函數中的第二個參數factor參數指定.比如說,假如factor是2,那么如果第一個slabclass_t的size是unsigned int size = sizeof(item) + settings.chunk_size;(也是在slabs_init函數中的語句),那么下一個slabclass_t的size就是size*factor(這里忽略對齊的因素).
于是乎,假設第一個slab能保存8byte的數據,factor為2,那么接下來的slab的size依次為16byte,32byte...
每次需要分配內存,都需要根據所需分配的尺寸查找大于該尺寸的最小尺寸的slab,比如還是前面的那個slab模型,如果現在需要分配30byte的空間,查找得到大于30byte的最小slab尺寸是32byte,于是就從這個slab中查找item分配給它.
但是這里有一個問題,就是多余資源的浪費,前面說的30byte只是浪費了2byte,但是如果現在要分配的是17byte,那么就浪費了15byte,浪費了將近50%!因此才有了前面需要指定factor的原因,使用者可以根據需要指定不同的增長factor,以降低資源的浪費.
2) 淘汰
淘汰采用的是LRU算法,所有的最近使用的item保存在static item *tails[LARGEST_ID];(item.c)中,已經分配的內存會以鏈表的形式保存在這個數組中,如果對應的slab已經分配不到足夠的內存,就到這個鏈表中查詢,淘汰的依據是item結構體中的exptime字段.
簡單分析到此,需要更詳細的解釋就去看代碼吧,memcached中與這部分的代碼在slab.h(.c)/item.h(.c)中,兩個關鍵的結構體是item和slabclass_t.