内核中的链表list_head

本文介绍了Linux内核中链表的具体实现方式,包括链表的初始化和遍历方法。通过对核心代码片段的解析,展示了如何将链表节点嵌入到数据结构中,并提供了具体的宏定义和内联函数示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在linux内核中,链表的实现是通过把链表结点嵌入到数据结构中。
如:
struct cx18_buffer {
 struct list_head list;
 dma_addr_t dma_handle;
 char *buf;
 u32 bytesused;
 u32 readpos;
};
链表结构体的定义在include\linux\types.h中:
struct list_head {
 struct list_head *next, *prev;
};
操作在include\linux\list.h中实现。
1、链表的初始化
#define  LIST_HEAD_INIT(name)  { &(name), &(name) }
#define LIST_HEAD(name) \
 struct list_head name = LIST_HEAD_INIT(name)               /*定义一个list_head的变量,并分别对next和prev赋值,初始化为空链表*/
static inline void INIT_LIST_HEAD(struct list_head *list)     /*初始化list为空链表,它是一个内联函数*/
{
 list->next = list;
 list->prev = list;
}

2、链表的遍历
/***
* pos是list_head的一个临时指针变量,用来指向当前项,head是头结点,访问的开始位置,
* prefetch用来预取下一条要访问的数据,提高访问速度。
*/
#define list_for_each(pos, head) \
 for (pos = (head)->next; prefetch(pos->next), pos != (head); \
         pos = pos->next)
/***
* pos仍然是临时变量,只不过它是你用的数据结构的结构体指针了。
* head是list_head类型的指针,你要访问的开始位置。
* member是pos中list_head结构的变量名。
* list_for_each_entry相对于list_for_each来说,每次能访问到的是数据结构指针,而不是链表指针了,
* 因为里面包含了list_entry这个宏list_entry的定义如下:
#define list_entry(ptr, type, member)   container_of(ptr, type, member)
*/
#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))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值