您的位置:首页 > 运维架构 > Linux

linux内核(2.6)中的双循环链表浅析

2009-11-23 22:05 204 查看
Linux 2.6内核链表数据结构的实现

在计算机科学中,链表是非常通用的数据结构,贯穿于整个linux的内核。在linux内核中,链表通常以
双循环链表的方式出现。所有链表的代码在include/linux/list.h文件中。
定义如下:
struct list_head {
struct list_head *next, *prev;
};


这里的list_head没有数据域。在Linux内核链表中,不是在链表结构中包含数据,而是在数据结构中包含链表。
list.h还定义了许多使用的宏和内联函数,下面介绍几个典型的:

#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;
}


在linux的宏定义中,时常用到do{}while(0),这是为了方便再宏定义中包含多行代码,
关于这个的说明在网上可以找到很多详细的介绍。
在宏INIT_LIST_HEAD中,将它初始化为前后都指向自己

在linux内核的链表中,一个空链表定义如下: head->next指向链表的头元素。

list.h中还定义了 list_add() , list_add_tail(),list_del()等基本的链表操作函数,都是比较简单的
C语言这里不详述。

在list.h中极其有用的一个宏是list_for_each_entry
#define list_for_each_entry(pos, head, member)				/
for (pos = list_entry((head)->next, typeof(*pos), member);	/
prefetch(pos->member.next), &pos->member != (head); 	/
pos = list_entry(pos->member.next, typeof(*pos), member))

它可以遍历整个链表,在linux用的非常广泛,例如当CPU开始工作时,激活在工作队列中的每个进程
-----------------------------------------------------------------------------
kernel/workqueue.c
59 struct workqueue_struct {
60 struct cpu_workqueue_struct cpu_wq[NR_CPUS];
61 const char *name;
62 struct list_head list; /* Empty if single thread */
63 };
...
466 case CPU_ONLINE:
467 /* Kick off worker threads. */
468 list_for_each_entry(wq, &workqueues, list)
469 wake_up_process(wq->cpu_wq[hotcpu].thread);
470 break;
-----------------------------------------------------------------------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: