Linux源码-通用双向链表的实现

我们之前在数据结构课程中学习的链表都是将数据放在链表节点中,然后将这些节点串成一个链表。例如:

c 复制代码
typedef struct Node {
    Node* prev;
    Node* next;
    
    T data_obj;
};

void addHead(Node* head, T data_obj);
......

这种实现方案直观容易理解,但是对于C语言这种非泛型的语言来说,需要为每个需要使用链表的数据结构都定义链表节点和一套链表操作,有没有更优雅的实现方案?

有的兄弟!Linux使用C语言开发,并且其各个模块中大量使用了链表。Linux的解决方案可以总结为一句话:"不将数据对象放在链表节点中,而是将链表节点存储在数据对象中"。

例如include/linux/mm.h中的mem_map_t数据结构:

c 复制代码
typedef struct page {
    struct list_head list;
......
    struct list_head lru;
......
} mem_map_t;

其中使用了两个链表,Linux并不是定义了两种链表节点同时管理该数据结构,而是在该数据结构中插入了两个链表节点。

关键问题:根据宿主结构体找list_head容易,但是如何根据list_head找到宿主结构体?

list_head的实现在include/linux/list.h中:

c 复制代码
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);
}

其中链表的初始化和链表操作都很简单。重点关注如何根据链表节点指针,找到其宿主结构体的首地址,实现方法在宏函数list_entry()中:

c 复制代码
#define list_entry(ptr, type, member) \
    ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))

参数解释:

  • ptr,list_head节点的地址
  • type,宿主结构体的类型,例如上例中的struct page
  • member,ptr指向的list_head在宿主结构体中的字段名,例如上例中的lru

其中(&((type *)0)->member)))表示的是假设将0作为宿主结构体的起始地址,然后取其member的地址(其实就是member字段在宿主结构体中的偏移)。然后使用ptr减去该偏移,就得到了宿主结构体的首地址。

相关推荐
贵州诚鑫致达科技有限公司12 小时前
Linux的yum源怎么重启?源不是服务
linux·运维·服务器
澜山奕秋16 小时前
RHCSA
linux·运维·服务器
Web极客码16 小时前
告别流式截断:我用客户端中间件解决长文本 API 跨国 SSE 断连与数据自愈
linux·agent 图
cnnews17 小时前
Chromebox3安装Ubuntu后内存化与最小化 eMMC 写入优化
linux·运维·ubuntu
flytalei17 小时前
Ubuntu 24.04 单节点 K3s 部署实践:从环境评估到故障排查与验收
linux·运维·ubuntu
Starry-sky(jing)17 小时前
Hermes Agent 部署后怎么升级?v0.21.7 Linux 源代码版实测
linux·人工智能·ai agent·版本升级·hermes agent
水饺编程18 小时前
第2章:Linux 基础,clear 命令
linux·c语言·汇编
GeW18 小时前
新质生产力路线图Linux和数据库自主可控实践指南
linux
yunwei3718 小时前
eBPF 教程:BPF 迭代器用于内核数据导出
linux·后端·性能优化
别动我齐刘海19 小时前
实时控制学习2
linux·c++·人工智能·学习·算法