文章目录
内核源码分析
双链表数据结构定义
循环双链表定义位于 linux-2.6.27\include\linux\list.h
中,定义如下。该结构只定义了两个指针 *next
和 *prev
,均指向 list_head
结构,数据结构中并不包括具体的数据,这样的好处是,可以最大程度实现复用,具体实现时,将 list_head
结构嵌入到其他数据结构中即可。
struct list_head {
struct list_head *next, *prev;
};
使用上述结构可以实现多种数据结构,去掉一个指针域即变为单链表;从头部插入删除则变为栈;从头部插入尾部取则变为队列;将 *next
和 *prev
看作左右孩子节点则变为二叉树。故双链表结构是内核源码中重要的数据结构。
双链表头节点定义宏
有两个相关宏,定义如下,可以看到,LIST_HEAD
调用了 LIST_HEAD_INIT
宏。向LIST_HEAD
宏传入参数 name
,生成一个名为 name
的 struct list_head
结构,name.next
和 name.prve
指针均指向 name
自身。
#define LIST_HEAD_INIT(name) { &(name), &(name) }
#define LIST_HEAD(name) \
struct list_head name = LIST_HEAD_INIT(name)
上述两个宏可以以如下方式调用,两种调用异曲同工,都生命并初始化一个双链表头节点,执行后效果如图所示。
LIST_HEAD(head);
struct list_head head;
LIST_HEAD_INIT(head);
双链表头节点初始化函数
init_list_head
定义如下,static
修饰说明该函数仅在当前文件(即 list.h
)使用,inline
将该函数定义为内联函数,程序中任何使用该函数的地方将直接用函数体替换该函数调用,从而减少函数调用带来的额外开销。参数为 struct list_head
结构的指针 list
,函数体中仅仅执行两条语句,将 list 的前驱和后向指针分别指向 list
自身。
static inline void INIT_LIST_HEAD(struct list_head *list)
{
list->next = list;
list->prev = list;
}
用于循环双链表结构处理的函数
1. __list_add() 函数
以下是该函数代码,注释很清晰,该函数的作用是在两个节点间插入一个新节点,且该函数只用于内部链表的处理,要已知要插入节点的前后节点。
/*
* Insert a new entry between two known consecutive entries.
*
* This is only for internal list manipulation where we know
* the prev/next entries already!
*/
#ifndef CONFIG_DEBUG_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;
}
#else
extern void __list_add