Linux內核中雙向鏈表的經典實現

概要

       本文對雙向鏈表進行探討,介紹的內容是Linux內核中雙向鏈表的經典實現和用法。其中,也會涉及到Linux內核中非常常用的兩個經典宏定義offsetof和container_of。內容包括:
1.Linux中的兩個經典宏定義
2.Linux中雙向鏈表的經典實現
       

Linux中的兩個經典宏定義

       倘若你查看過Linux Kernel的源碼,那麼你對 offsetof 和 container_of 這兩個宏應該不陌生。這兩個宏最初是極客寫出的,後來在Linux內核中被推廣使用。
1.offsetof
1.1 offsetof介紹
定義:offsetof在linux內核的include/linux/stddef.h中定義。

1 #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

說明:獲得結構體(TYPE)的變量成員(MEMBER)在此結構體中的偏移量。
       (01) ( (TYPE *)0 ) 將零轉型爲TYPE類型指針,即TYPE類型的指針的地址是0。
       (02) ((TYPE *)0)->MEMBER 訪問結構中的數據成員。
       (03) &( ( (TYPE )0 )->MEMBER ) 取出數據成員的地址。由於TYPE的地址是0,這裏獲取到的地址就是相對MEMBER在TYPE中的偏移。 (04) (size_t)(&(((TYPE)0)->MEMBER)) 結果轉換類型。對於32位系統而言,size_t是unsigned int類型;對於64位系統而言,size_t是unsigned long類型。
1.2 offsetof示例
代碼(offset_test.c):

 1 #include <stdio.h>
 2 // 獲得結構體(TYPE)的變量成員(MEMBER)在此結構體中的偏移量。
 3 #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
 4 struct student
 5 {
 6     char gender;
 7     int id;
 8     int age;
 9     char name[20];
10 };
11
12 void main()
13 {
14     int gender_offset, id_offset, age_offset, name_offset;
15     gender_offset = offsetof(struct student, gender);
16     id_offset = offsetof(struct student, id);
17     age_offset = offsetof(struct student, age);
18     name_offset = offsetof(struct student, name);
19     printf("gender_offset = %d\n", gender_offset);
20     printf("id_offset = %d\n", id_offset);
21     printf("age_offset = %d\n", age_offset);
22     printf("name_offset = %d\n", name_offset);
23 }

結果:

1 gender_offset = 0
2 id_offset = 4
3 age_offset = 8
4 name_offset = 12

說明:簡單說說"爲什麼id的偏移值是4,而不是1"。我的運行環境是linux系統,32位的x86架構。這就意味着cpu的數據總線寬度爲32,每次能夠讀取4字節數據。gcc對代碼進行處理的時候,是按照4字節對齊的。所以,即使gender是char(一個字節)類型,但是它仍然是4字節對齊的!
1.3 offsetof圖解

       TYPE是結構體,它代表"整體";而MEMBER是成員,它是整體中的某一部分。
       將offsetof看作一個數學問題來看待,問題就相當簡單了:已知'整體'和該整體中'某一個部分',而計算該部分在整體中的偏移
2.container_of
2.1 container_of介紹
定義:container_of在linux內核的include/linux/kernel.h中定義。

1 #define container_of(ptr, type, member) ({          \
2     const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
3     (type *)( (char *)__mptr - offsetof(type,member) );})

說明:根據"結構體(type)變量"中的"域成員變量(member)的指針(ptr)"來獲取指向整個結構體變量的指針。
       (01) typeof( ( (type *)0)->member ) 取出member成員的變量類型。
       (02) const typeof( ((type *)0)->member ) *__mptr = (ptr) 定義變量__mptr指針,並將ptr賦值給__mptr。經過這一步,__mptr爲member數據類型的常量指針,其指向ptr所指向的地址。
       (04) (char *)__mptr 將__mptr轉換爲字節型指針。
       (05) offsetof(type,member)) 就是獲取"member成員"在"結構體type"中的位置偏移。
       (06) (char *)__mptr - offsetof(type,member)) 就是用來獲取"結構體type"的指針的起始地址(爲char *型指針)。
       (07) (type *)( (char *)__mptr - offsetof(type,member) ) 就是將"char *類型的結構體type的指針"轉換爲"type *類型的結構體type的指針"。
2.2 container_of示例
代碼(container_test.c):

 1 #include <stdio.h>
 2 #include <string.h>
 3 // 獲得結構體(TYPE)的變量成員(MEMBER)在此結構體中的偏移量。
 4 #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
 5 // 根據"結構體(type)變量"中的"域成員變量(member)的指針(ptr)"來獲取指向整個結構體變量的指針
 6 #define container_of(ptr, type, member) ({          \
 7     const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
 8     (type *)( (char *)__mptr - offsetof(type,member) );})
 9 struct student
10 {
11     char gender;
12     int id;
13     int age;
14     char name[20];
15 };
16
17 void main()
18 {
19     struct student stu;
20     struct student *pstu;
21     stu.gender = '1';
22     stu.id = 9527;
23     stu.age = 24;
24     strcpy(stu.name, "zhouxingxing");
25     // 根據"id地址" 獲取 "結構體的地址"。
26     pstu = container_of(&stu.id, struct student, id);
27     // 根據獲取到的結構體student的地址,訪問其它成員
28     printf("gender= %c\n", pstu->gender);
29     printf("age= %d\n", pstu->age);
30     printf("name= %s\n", pstu->name);
31 }

結果:

1 gender= 1
2 age= 24
3 name= zhouxingxing

2.3 container_of圖解

       type是結構體,它代表"整體";而member是成員,它是整體中的某一部分,而且member的地址是已知的。
       將offsetof看作一個數學問題來看待,問題就相當簡單了:已知'整體'和該整體中'某一個部分',要根據該部分的地址,計算出整體的地址。

Linux中雙向鏈表的經典實現

1.Linux中雙向鏈表介紹
Linux雙向鏈表的定義主要涉及到兩個文件:
include/linux/types.h
include/linux/list.h
Linux中雙向鏈表的使用思想
       它是將雙向鏈表節點嵌套在其它的結構體中;在遍歷鏈表的時候,根據雙鏈表節點的指針獲取"它所在結構體的指針",從而再獲取數據。
       我舉個例子來說明,可能比較容易理解。假設存在一個社區中有很多人,每個人都有姓名和年齡。通過雙向鏈表將人進行關聯的模型圖如下:

       person代表人,它有name和age屬性。爲了通過雙向鏈表對person進行鏈接,我們在person中添加了list_head屬性。通過list_head,我們就將person關聯起來了。

1 struct person 
2 { 
3     int age; 
4     char name[20];
5     struct list_head list; 
6 };

2.Linux中雙向鏈表的源碼分析
(01). 節點定義

1 struct list_head {
2     struct list_head *next, *prev;
3 };

 雖然名稱list_head,但是它既是雙向鏈表的表頭,也代表雙向鏈表的節點。
(02). 初始化節點

1 #define LIST_HEAD_INIT(name) { &(name), &(name) }
2 #define LIST_HEAD(name) \
3     struct list_head name = LIST_HEAD_INIT(name)
4 static inline void INIT_LIST_HEAD(struct list_head *list)
5 {
6     list->next = list;
7     list->prev = list;
8 }

       LIST_HEAD的作用是定義表頭(節點):新建雙向鏈表表頭name,並設置name的前繼節點和後繼節點都是指向name本身。
       LIST_HEAD_INIT的作用是初始化節點:設置name節點的前繼節點和後繼節點都是指向name本身。
       INIT_LIST_HEAD和LIST_HEAD_INIT一樣,是初始化節點:將list節點的前繼節點和後繼節點都是指向list本身。
(03). 添加節點

 1 static inline void __list_add(struct list_head *new,
 2                   struct list_head *prev,
 3                   struct list_head *next)
 4 {
 5     next->prev = new;
 6     new->next = next;
 7     new->prev = prev;
 8     prev->next = new;
 9 }
10
11 static inline void list_add(struct list_head *new, struct list_head *head)
12 {
13     __list_add(new, head, head->next);
14 }
15
16 static inline void list_add_tail(struct list_head *new, struct list_head *head)
17 {
18     __list_add(new, head->prev, head);
19 }

       list_add(new, prev, next)的作用是添加節點:將new插入到prev和next之間。在linux中,以""開頭的函數意味着是內核的內部接口,外部不應該調用該接口。
       list_add(new, head)的作用是添加new節點:將new添加到head之後,是new稱爲head的後繼節點。
       list_add_tail(new, head)的作用是添加new節點:將new添加到head之前,即將new添加到雙鏈表的末尾。
(04). 刪除節點

 1 static inline void __list_del(struct list_head * prev, struct list_head * next)
 2 {
 3     next->prev = prev;
 4     prev->next = next;
 5 }
 6
 7 static inline void list_del(struct list_head *entry)
 8 {
 9     __list_del(entry->prev, entry->next);
10 }
11
12 static inline void __list_del_entry(struct list_head *entry)
13 {
14     __list_del(entry->prev, entry->next);
15 }
16
17 static inline void list_del_init(struct list_head *entry)
18 {
19     __list_del_entry(entry);
20     INIT_LIST_HEAD(entry);
21 }

__list_del(prev, next) 和__list_del_entry(entry)都是linux內核的內部接口。
__list_del(prev, next) 的作用是從雙鏈表中刪除prev和next之間的節點。
__list_del_entry(entry) 的作用是從雙鏈表中刪除entry節點。

list_del(entry) 和 list_del_init(entry)是linux內核的對外接口。
list_del(entry) 的作用是從雙鏈表中刪除entry節點。
list_del_init(entry) 的作用是從雙鏈表中刪除entry節點,並將entry節點的前繼節點和後繼節點都指向entry本身。
(05). 替換節點

1 static inline void list_replace(struct list_head *old,
2                 struct list_head *new)
3 {
4     new->next = old->next;
5     new->next->prev = new;
6     new->prev = old->prev;
7     new->prev->next = new;
8 }

list_replace(old, new)的作用是用new節點替換old節點。
(06). 判斷雙鏈表是否爲空

1 static inline int list_empty(const struct list_head *head)
2 {
3     return head->next == head;
4 }

       list_empty(head)的作用是判斷雙鏈表是否爲空。它是通過區分"表頭的後繼節點"是不是"表頭本身"來進行判斷的。
(07). 獲取節點

1 #define list_entry(ptr, type, member) \
2     container_of(ptr, type, member)

       list_entry(ptr, type, member) 實際上是調用的container_of宏。
       它的作用是:根據"結構體(type)變量"中的"域成員變量(member)的指針(ptr)"來獲取指向整個結構體變量的指針。
(08). 遍歷節點

1 #define list_for_each(pos, head) \
2     for (pos = (head)->next; pos != (head); pos = pos->next)
3
4 #define list_for_each_safe(pos, n, head) \
5     for (pos = (head)->next, n = pos->next; pos != (head); \
6         pos = n, n = pos->next)

       list_for_each(pos, head)和list_for_each_safe(pos, n, head)的作用都是遍歷鏈表。但是它們的用途不一樣!
       list_for_each(pos, head)通常用於獲取節點,而不能用到刪除節點的場景。
       list_for_each_safe(pos, n, head)通常刪除節點的場景。
3.Linux中雙向鏈表的使用示例
雙向鏈表代碼(list.h):

 1 #ifndef _LIST_HEAD_H
 2 #define _LIST_HEAD_H
 3 // 雙向鏈表節點
 4 struct list_head {
 5     struct list_head *next, *prev;
 6 };
 7
 8 // 初始化節點:設置name節點的前繼節點和後繼節點都是指向name本身。
 9 #define LIST_HEAD_INIT(name) { &(name), &(name) }
10 // 定義表頭(節點):新建雙向鏈表表頭name,並設置name的前繼節點和後繼節點都是指向name本身。
11 #define LIST_HEAD(name) \
12     struct list_head name = LIST_HEAD_INIT(name)
13 // 初始化節點:將list節點的前繼節點和後繼節點都是指向list本身。
14 static inline void INIT_LIST_HEAD(struct list_head *list)
15 {
16     list->next = list;
17     list->prev = list;
18 }
19
20 // 添加節點:將new插入到prev和next之間。
21 static inline void __list_add(struct list_head *new,
22                   struct list_head *prev,
23                   struct list_head *next)
24 {
25     next->prev = new;
26     new->next = next;
27     new->prev = prev;
28     prev->next = new;
29 }
30
31 // 添加new節點:將new添加到head之後,是new稱爲head的後繼節點。
32 static inline void list_add(struct list_head *new, struct list_head *head)
33 {
34     __list_add(new, head, head->next);
35 }
36
37 // 添加new節點:將new添加到head之前,即將new添加到雙鏈表的末尾。
38 static inline void list_add_tail(struct list_head *new, struct list_head *head)
39 {
40     __list_add(new, head->prev, head);
41 }
42
43 // 從雙鏈表中刪除entry節點。
44 static inline void __list_del(struct list_head * prev, struct list_head * next)
45 {
46     next->prev = prev;
47     prev->next = next;
48 }
49
50 // 從雙鏈表中刪除entry節點。
51 static inline void list_del(struct list_head *entry)
52 {
53     __list_del(entry->prev, entry->next);
54 }
55
56 // 從雙鏈表中刪除entry節點。
57 static inline void __list_del_entry(struct list_head *entry)
58 {
59     __list_del(entry->prev, entry->next);
60 }
61
62 // 從雙鏈表中刪除entry節點,並將entry節點的前繼節點和後繼節點都指向entry本身。
63 static inline void list_del_init(struct list_head *entry)
64 {
65     __list_del_entry(entry);
66     INIT_LIST_HEAD(entry);
67 }
68
69 // 用new節點取代old節點
70 static inline void list_replace(struct list_head *old,
71                 struct list_head *new)
72 {
73     new->next = old->next;
74     new->next->prev = new;
75     new->prev = old->prev;
76     new->prev->next = new;
77 }
78
79 // 雙鏈表是否爲空
80 static inline int list_empty(const struct list_head *head)
81 {
82     return head->next == head;
83 }
84 // 獲取"MEMBER成員"在"結構體TYPE"中的位置偏移
85 #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
86 // 根據"結構體(type)變量"中的"域成員變量(member)的指針(ptr)"來獲取指向整個結構體變量的指針
87 #define container_of(ptr, type, member) ({          \
88     const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
89     (type *)( (char *)__mptr - offsetof(type,member) );})
90 // 遍歷雙向鏈表
91 #define list_for_each(pos, head) \
92     for (pos = (head)->next; pos != (head); pos = pos->next)
93 #define list_for_each_safe(pos, n, head) \
94     for (pos = (head)->next, n = pos->next; pos != (head); \
95         pos = n, n = pos->next)
96 #define list_entry(ptr, type, member) \
97     container_of(ptr, type, member)
98 #endif

雙向鏈表測試代碼(test.c):

 1 #include <stdio.h> 
 2 #include <stdlib.h>
 3 #include <string.h>
 4 #include "list.h" 
 5 struct person 
 6 { 
 7     int age; 
 8     char name[20];
 9     struct list_head list; 
10 };
11
12 void main(int argc, char* argv[]) 
13 { 
14     struct person *pperson; 
15     struct person person_head; 
16     struct list_head *pos, *next; 
17     int i;
18     // 初始化雙鏈表的表頭 
19     INIT_LIST_HEAD(&person_head.list); 
20     // 添加節點
21     for (i=0; i<5; i++)
22     {
23         pperson = (struct person*)malloc(sizeof(struct person));
24         pperson->age = (i+1)*10;
25         sprintf(pperson->name, "%d", i+1);
26         // 將節點鏈接到鏈表的末尾 
27         // 如果想把節點鏈接到鏈表的表頭後面,則使用 list_add
28         list_add_tail(&(pperson->list), &(person_head.list));
29     }
30
31     // 遍歷鏈表
32     printf("==== 1st iterator d-link ====\n"); 
33     list_for_each(pos, &person_head.list) 
34     { 
35         pperson = list_entry(pos, struct person, list); 
36         printf("name:%-2s, age:%d\n", pperson->name, pperson->age); 
37     } 
38
39     // 刪除節點age爲20的節點
40     printf("==== delete node(age:20) ====\n");
41     list_for_each_safe(pos, next, &person_head.list)
42     {
43         pperson = list_entry(pos, struct person, list);
44         if(pperson->age == 20)
45         {
46             list_del_init(pos);
47             free(pperson);
48         }
49     }
50
51     // 再次遍歷鏈表
52     printf("==== 2nd iterator d-link ====\n");
53     list_for_each(pos, &person_head.list)
54     {
55         pperson = list_entry(pos, struct person, list);
56         printf("name:%-2s, age:%d\n", pperson->name, pperson->age);
57     }
58
59     // 釋放資源
60     list_for_each_safe(pos, next, &person_head.list)
61     {
62         pperson = list_entry(pos, struct person, list); 
63         list_del_init(pos); 
64         free(pperson); 
65     }      
66 }

運行結果:

 1 ==== 1st iterator d-link ====
 2 name:1 , age:10
 3 name:2 , age:20
 4 name:3 , age:30
 5 name:4 , age:40
 6 name:5 , age:50
 7 ==== delete node(age:20) ====
 8 ==== 2nd iterator d-link ====
 9 name:1 , age:10
10 name:3 , age:30
11 name:4 , age:40
12 name:5 , age:50

 

文章來源:
http://www.cnblogs.com/skywang12345/p/3562146.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章