仰慕kernel的list.h良久了,還記得以前o2的李大哥號稱list.h飄逸寫手...自己也曾經(jīng)牛刀小試過一把.今日得閑,暫探索性的分析一把.
1. 簡約而又不簡單的鏈表定義
于雙向鏈表而言,內(nèi)核中定義了如下簡單結(jié)構(gòu):
struct list_head {
struct list_head *next, *prev;
};
這個不含任何數(shù)據(jù)項的結(jié)構(gòu),注定了它的通用性和未來使用的靈活性,例如前面的例子就可以按如下方式定義:
struct my_list{
void *mydata;
struct list_head list;
};
在此,進一步說明幾點:
1)list字段,隱藏了鏈表的指針特性,但正是它,把我們要鏈接的數(shù)據(jù)組織成了鏈表。
2)struct list_head可以位于結(jié)構(gòu)的任何位置
3)可以給struct list_head起任何名字。
4)在一個結(jié)構(gòu)中可以有多個list
例如,我們對要完成的任務進行描述,而任務中又包含子任務,于是有如下結(jié)構(gòu):
-------------------------------------------------------------------------------------------------------------------------
struct todo_tasks{
char *task_name;
unsigned int name_len;
short int status;
int sub_tasks;
int subtasks_completed;
struct list_head completed_subtasks;/* 已完成的子任務形成鏈表 */
int subtasks_waiting;
struct list_head waiting_subtasks; /* 待完成的子任務形成鏈表 */
struct list_head todo_list; /* 要完成的任務形成鏈表 */
};
-----------------------------------------------------------------------
簡約而又不簡單struct list_head,以此為基本對象,就衍生了對鏈表的插入、刪除、合并以及遍歷等各種操作:
2. 鏈表的聲明和初始化宏
實際上, struct list_head只定義了鏈表節(jié)點,并沒有專門定義鏈表頭,那么一個鏈表結(jié)構(gòu)是如何建立起來的?讓我們來看看下面兩個宏:
#define LIST_HEAD_INIT(name) { &(name), &(name) }
#define LIST_HEAD(name) struct list_head name = LIST_HEAD_INIT(name)
如果我們要申明并定義自己的鏈表頭mylist,直接調(diào)用LIST_HEAD:
LIST_HEAD(mylist)
則mylist的next、prev指針都初始化為指向自己,這樣,我們就有了一個空鏈表,如何判斷鏈表是否為空,自己寫一下這個簡單的函數(shù)list_empty ,也就是讓頭指針的next指向自己而已。
3. staitic inline函數(shù)-隱藏并展開
在list.h中定義的函數(shù)大都是 staitic inline f()形式?為什么這樣定義?
關(guān)鍵字“static”加在函數(shù)前,表示這個函數(shù)是靜態(tài)函數(shù),所謂靜態(tài)函數(shù),實際上是對函數(shù)作用域的限制,指該函數(shù)的作用域僅
局限于本文件。所以說,static具有信息隱藏作用。
而關(guān)鍵字"inline“加在函數(shù)前,說明這個函數(shù)對編譯程序是可見的,也就是說,編譯程序在調(diào)用這個函數(shù)時就立即展開該函數(shù)。所以,關(guān)鍵字inline 必須與函數(shù)定義體放在一起才能使函數(shù)成為內(nèi)聯(lián)。inline函數(shù)一般放在頭文件中。
4. 無處不在的隱藏特性
我們分析一下在鏈表中增加一個節(jié)點的函數(shù)實現(xiàn):
有三個函數(shù):
static inline void __list_add();
static inline void list_add();
static inline void list_add_tail();
-------------------------------------------------------------------------------------------------
/*
* Insert a new entry between two known consecutive entries.
*
* This is only for internal list manipulation where we know
* the prev/next entries already!
*/
static inline void __list_add(struct list_head *new,
struct list_head *prev,
struct list_head *next)
{
next->prev = new;
new->next = next;
new->prev = prev;
prev->next = new;
}
--------------------------------------------------------------------------------------------------
/**
* list_add - add a new entry
* @new: new entry to be added
* @head: list head to add it after
*
* Insert a new entry after the specified head.
* This is good for implementing stacks.
*/
static inline void list_add(struct list_head *new, struct list_head *head)
{
__list_add(new, head, head->next);
}
--------------------------------------------------------------------------------------------------
/**
* list_add_tail - add a new entry
* @new: new entry to be added
* @head: list head to add it before
*
* Insert a new entry before the specified head.
* This is useful for implementing queues.
*/
static inline void list_add_tail(struct list_head *new, struct list_head *head)
{
__list_add(new, head->prev, head);
}
--------------------------------------------------------------------------------------------------
仔細體會其實現(xiàn)代碼,看起來簡單有效,但實際上也是一種抽象和封裝的體現(xiàn)。首先__list_add()函數(shù)做基本的操作,該函數(shù)僅僅是增加一個節(jié)點,至于這個節(jié)點加到何處,暫不考慮。list_add()調(diào)用__list_add()這個內(nèi)部函數(shù),在鏈表頭增加一個節(jié)點,實際上實現(xiàn)了棧在頭部增加節(jié)點的操作,而list_add_tail()在尾部增加一個節(jié)點,實際上實現(xiàn)了隊的操作。
至于鏈表的刪除、搬移和合并,比較簡單,不再此一一討論
5. 鏈表遍歷-似走過千山萬水
遍歷鏈表本是簡單的,list.h中就定義了如下的宏:
--------------------------------------------------------------------------------------------------
**
* list_for_each - iterate over a list
* @pos: the &struct list_head to use as a loop counter.
* @head: the head for your list.
*/
#define list_for_each(pos, head) \
for (pos = (head)->next; pos != (head); \
pos = pos->next)
--------------------------------------------------------------------------------------------------
這種遍歷僅僅是找到一個個節(jié)點在鏈表中的位置pos,難點在于,如何通過pos獲得節(jié)點的地址,從而可以使用節(jié)點中的數(shù)據(jù)? 于是 list.h中定義了晦澀難懂的list_entry()宏:
--------------------------------------------------------------------------------------------------
/**
* list_entry - get the struct for this entry
* @ptr: the &struct list_head pointer.
* @type: the type of the struct this is embedded in.
* @member: the name of the list_struct within the struct.
*/
#define list_entry(ptr, type, member) \
((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))
--------------------------------------------------------------------------------------------------
指針ptr指向結(jié)構(gòu)體type中的成員member;通過指針ptr,返回結(jié)構(gòu)體type的起始地址,如圖2。
type
|----------|
| |
| |
|----------|
ptr--> | member --|
|----------|
| |
| |
|----------|
圖2 list_entry()宏的示意圖
為了便于理解,在此給予進一步說明。
例如
my_list結(jié)構(gòu):struct my_list{
void *mydata;
struct list_head list;
};
struct list_head *pos; 則list_entry(pos, mylist, list)宏,就可以根據(jù)pos的值,獲取mylist的地址,也就是指向mylist的指針,這樣,我們就可以存取mylist->mydata字段了。
可為什么能夠達到這樣的效果?
list_entry(pos, mylist, list) 展開以后為:
(
(struct my_list *
)((char *)(pos) - (unsigned long)
(&
((struct my_list *)0
)->list
)))
這看起來會使大多數(shù)人眩暈,但仔細分析一下,實際很簡單。
((size_t) &(type*)0)->member)把0地址轉(zhuǎn)化為type結(jié)構(gòu)的指針,然后獲取該結(jié)構(gòu)中member成員的指針,并將其強制轉(zhuǎn)換為size_t類型。于是,由于結(jié)構(gòu)從0地址開始定義,因此,這樣求出member的成員地址,實際上就是它在結(jié)構(gòu)中的偏移量。為了更好的理解這些,我們可以寫一段程序來驗證:
---------------------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
struct foobar{
unsigned int foo;
char bar;
char boo;
};
int main(int argc, char** argv){
struct foobar tmp;
printf("address of &tmp is= %p\n\n", &tmp);
printf("address of tmp->foo= %p \t offset of tmp->foo= %lu\n", &tmp.foo, (unsigned long) &((struct foobar *)0)->foo);
printf("address of tmp->bar= %p \t offset of tmp->bar= %lu\n", &tmp.bar, (unsigned long) &((struct foobar *)0)->bar);
printf("address of tmp->boo= %p \t offset of tmp->boo= %lu\n\n", &tmp.boo, (unsigned long) &((struct foobar *)0)->boo);
printf("computed address of &tmp using:\n");
printf("\taddress and offset of tmp->foo= %p\n",
(struct foobar *) (((char *) &tmp.foo) - ((unsigned long) &((struct foobar *)0)->foo)));
printf("\taddress and offset of tmp->bar= %p\n",
(struct foobar *) (((char *) &tmp.bar) - ((unsigned long) &((struct foobar *)0)->bar)));
printf("\taddress and offset of tmp->boo= %p\n",
(struct foobar *) (((char *) &tmp.boo) - ((unsigned long) &((struct foobar *)0)->boo)));
return 0;
}
Output from this code is:
address of &tmp is= 0xbfffed00
address of tmp->foo= 0xbfffed00 offset of tmp->foo= 0
address of tmp->bar= 0xbfffed04 offset of tmp->bar= 4
address of tmp->boo= 0xbfffed05 offset of tmp->boo= 5
computed address of &tmp using:
address and offset of tmp->foo= 0xbfffed00
address and offset of tmp->bar= 0xbfffed00
address and offset of tmp->boo= 0xbfffed00
----------------------------------------------------------------------------------------
到此,我們對鏈表的實現(xiàn)機制有所了解,但在此止步的話,我們依然無法領(lǐng)略這風景背后的韻味。
盡管list.h是內(nèi)核代碼中的頭文件,但我們可以把它移植到用戶空間使用。且看下一講,鏈表接口之應用。
[root@mip-123456 list]# cat list.h #ifndef _LINUX_LIST_H #define _LINUX_LIST_H
#define LIST_POISON1 ((void *) 0x00100100) #define LIST_POISON2 ((void *) 0x00200200)
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) #define container_of(ptr, type, member) ({\ const typeof( ((type *)0)->member ) *__mptr = (ptr);\ (type *)( (char *)__mptr - offsetof(type,member) );})
struct list_head { struct list_head *next, *prev; };
#define LIST_HEAD_INIT(name) { &(name), &(name) }
#define LIST_HEAD(name) \ struct list_head name = LIST_HEAD_INIT(name)
static inline void INIT_LIST_HEAD(struct list_head *list) { list->next = list; list->prev = list; }
static inline void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next) { next->prev = new; new->next = next; new->prev = prev; prev->next = new; }
static inline void list_add(struct list_head *new, struct list_head *head) { __list_add(new, head, head->next); }
static inline void list_add_tail(struct list_head *new, struct list_head *head) { __list_add(new, head->prev, head); }
static inline void __list_del(struct list_head * prev, struct list_head * next) { next->prev = prev; prev->next = next; }
static inline void list_del(struct list_head *entry) { __list_del(entry->prev, entry->next); entry->next = LIST_POISON1; entry->prev = LIST_POISON2; }
static inline void list_replace(struct list_head *old, struct list_head *new) { new->next = old->next; new->next->prev = new; new->prev = old->prev; new->prev->next = new; }
static inline void list_replace_init(struct list_head *old, struct list_head *new) { list_replace(old, new); INIT_LIST_HEAD(old); }
static inline void list_del_init(struct list_head *entry) { __list_del(entry->prev, entry->next); INIT_LIST_HEAD(entry); }
static inline void list_move(struct list_head *list, struct list_head *head) { __list_del(list->prev, list->next); list_add(list, head); }
static inline void list_move_tail(struct list_head *list, struct list_head *head) { __list_del(list->prev, list->next); list_add_tail(list, head); }
static inline int list_is_last(const struct list_head *list, const struct list_head *head) { return list->next == head; }
static inline int list_empty(const struct list_head *head) { return head->next == head; }
static inline int list_empty_careful(const struct list_head *head) { struct list_head *next = head->next; return (next == head) && (next == head->prev); }
static inline void __list_splice(struct list_head *list, struct list_head *head) { struct list_head *first = list->next; struct list_head *last = list->prev; struct list_head *at = head->next;
first->prev = head; head->next = first;
last->next = at; at->prev = last; }
static inline void list_splice(struct list_head *list, struct list_head *head) { if (!list_empty(list)) __list_splice(list, head); }
static inline void list_splice_init(struct list_head *list, struct list_head *head) { if (!list_empty(list)) { __list_splice(list, head); INIT_LIST_HEAD(list); } }
#define list_entry(ptr, type, member) \ container_of(ptr, type, member)
#define list_for_each(pos, head) \ for (pos = (head)->next;pos != (head); \ pos = pos->next)
#define __list_for_each(pos, head) \ for (pos = (head)->next; pos != (head); pos = pos->next)
#define list_for_each_prev(pos, head) \ for (pos = (head)->prev; pos != (head); \ pos = pos->prev)
#define list_for_each_safe(pos, n, head) \ for (pos = (head)->next, n = pos->next; pos != (head); \ pos = n, n = pos->next)
#define list_for_each_entry(pos, head, member) \ for (pos = list_entry((head)->next, typeof(*pos), member); \ &pos->member != (head); \ pos = list_entry(pos->member.next, typeof(*pos), member))
#define list_for_each_entry_reverse(pos, head, member) \ for (pos = list_entry((head)->prev, typeof(*pos), member); \ &pos->member != (head); \ pos = list_entry(pos->member.prev, typeof(*pos), member))
#define list_prepare_entry(pos, head, member) \ ((pos) ? : list_entry(head, typeof(*pos), member))
#define list_for_each_entry_continue(pos, head, member) \ for (pos = list_entry(pos->member.next, typeof(*pos), member); \ prefetch(pos->member.next), &pos->member != (head); \ pos = list_entry(pos->member.next, typeof(*pos), member))
#define list_for_each_entry_from(pos, head, member) \ for (; prefetch(pos->member.next), &pos->member != (head); \ pos = list_entry(pos->member.next, typeof(*pos), member))
#define list_for_each_entry_safe(pos, n, head, member) \ for (pos = list_entry((head)->next, typeof(*pos), member), \ n = list_entry(pos->member.next, typeof(*pos), member); \ &pos->member != (head); \ pos = n, n = list_entry(n->member.next, typeof(*n), member))
#define list_for_each_entry_safe_continue(pos, n, head, member) \ for (pos = list_entry(pos->member.next, typeof(*pos), member), \ n = list_entry(pos->member.next, typeof(*pos), member); \ &pos->member != (head); \ pos = n, n = list_entry(n->member.next, typeof(*n), member))
#define list_for_each_entry_safe_from(pos, n, head, member) \ for (n = list_entry(pos->member.next, typeof(*pos), member); \ &pos->member != (head); \ pos = n, n = list_entry(n->member.next, typeof(*n), member))
#define list_for_each_entry_safe_reverse(pos, n, head, member) \ for (pos = list_entry((head)->prev, typeof(*pos), member), \ n = list_entry(pos->member.prev, typeof(*pos), member); \ &pos->member != (head); \ pos = n, n = list_entry(n->member.prev, typeof(*n), member))
#endif
|
[root@mip-123456 list]# cat list.c #include <stdio.h> #include <stdlib.h>
#include "list.h"
struct jimmy_list{ int id; struct list_head list; char name[10]; };
int main(int argc, char **argv){
struct jimmy_list *tmp; struct list_head *pos, *q; unsigned int i;
struct jimmy_list mylist; INIT_LIST_HEAD(&mylist.list); /*初始化鏈表頭*/
for(i=0; i<5; i++){ tmp= (struct jimmy_list *)malloc(sizeof(struct jimmy_list)); tmp->id = i+1; sprintf(tmp->name, "jimmy %d", i+1);
/*list_add每次添加都是添加在list的第一個節(jié)點處*/ list_add(&(tmp->list), &(mylist.list)); } /*list 5->4->3->2->1*/
/*這里添加在尾部list_add_tail*/ for(i=5; i<7; i++){ tmp= (struct jimmy_list *)malloc(sizeof(struct jimmy_list)); tmp->id = i+1; sprintf(tmp->name, "kenthy %d", i+1); /*list_add每次添加都是添加在list的第一個節(jié)點處*/ list_add_tail(&(tmp->list), &(mylist.list)); } /*list 5->4->3->2->1->6->7*/
/*兩種遍歷list的方法--正向遍歷*/ printf("traversing the list using list_for_each()\n"); list_for_each(pos, &mylist.list){ tmp= list_entry(pos, struct jimmy_list, list); printf("id= %d name= %s\n", tmp->id, tmp->name); } printf("\n");
/*這里添加一個替換玩玩*/ #if 1 tmp= (struct jimmy_list *)malloc(sizeof(struct jimmy_list)); tmp->id = 55; sprintf(tmp->name, "kenthy %d", 55); INIT_LIST_HEAD(&(tmp->list)); list_replace((&mylist.list)->next,&(tmp->list)); #endif /*list 55->4->3->2->1->6->7*/
printf("traversing the list using list_for_each_entry()\n"); list_for_each_entry(tmp, &mylist.list, list) printf("id= %d name= %s\n", tmp->id, tmp->name); printf("\n");
/*兩種遍歷list的方法--反向遍歷*/ printf("reverse the list using list_for_each_prev()\n"); list_for_each_prev(pos, &mylist.list){ tmp= list_entry(pos, struct jimmy_list, list); printf("id= %d name= %s\n", tmp->id, tmp->name); } printf("\n"); printf("reverse the list using list_for_each_entry()\n"); list_for_each_entry_reverse(tmp, &mylist.list, list) printf("id= %d name= %s\n", tmp->id, tmp->name); printf("\n");
printf("deleting the list using list_for_each_safe()\n"); list_for_each_safe(pos, q, &mylist.list){ tmp= list_entry(pos, struct jimmy_list, list); printf("freeing item id= %d name= %s\n", tmp->id, tmp->name); list_del(pos); free(tmp); }
if(list_empty(&mylist.list)) printf("now the list if empty\n"); return 0; }
|
[root@mip-123456 list]# ./list traversing the list using list_for_each() id= 5 name= jimmy 5 id= 4 name= jimmy 4 id= 3 name= jimmy 3 id= 2 name= jimmy 2 id= 1 name= jimmy 1 id= 6 name= kenthy 6 id= 7 name= kenthy 7
traversing the list using list_for_each_entry() id= 55 name= kenthy 55 id= 4 name= jimmy 4 id= 3 name= jimmy 3 id= 2 name= jimmy 2 id= 1 name= jimmy 1 id= 6 name= kenthy 6 id= 7 name= kenthy 7
reverse the list using list_for_each_prev() id= 7 name= kenthy 7 id= 6 name= kenthy 6 id= 1 name= jimmy 1 id= 2 name= jimmy 2 id= 3 name= jimmy 3 id= 4 name= jimmy 4 id= 55 name= kenthy 55
reverse the list using list_for_each_entry() id= 7 name= kenthy 7 id= 6 name= kenthy 6 id= 1 name= jimmy 1 id= 2 name= jimmy 2 id= 3 name= jimmy 3 id= 4 name= jimmy 4 id= 55 name= kenthy 55
deleting the list using list_for_each_safe() freeing item id= 55 name= kenthy 55 freeing item id= 4 name= jimmy 4 freeing item id= 3 name= jimmy 3 freeing item id= 2 name= jimmy 2 freeing item id= 1 name= jimmy 1 freeing item id= 6 name= kenthy 6 freeing item id= 7 name= kenthy 7 now the list if empty
|