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)))

参数解释:

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

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

相关推荐
tang777897 分钟前
反爬虫场景下代理IP池的动态扩容与失效IP自动清理方案实现
linux·服务器·网络·爬虫代理·住宅代理ip
新时代牛马1 小时前
Linux 系统调用与IPC 完整篇:从syscall 入口、VDSO 到pipe/shm/futex 选型
linux·运维·服务器
fpcc2 小时前
计算机原理—Linux是如何加载可执行文件到内存
linux
野熊佩骑2 小时前
Kubernetes实战系列文章(三) 之 K8S运维常用命令
linux·运维·docker·微服务·云原生·容器·kubernetes
码农客栈2 小时前
linux 设备树下的 platform 驱动编写
linux
小HANN3 小时前
Linux建站实战:CentOS7+LNMP 从零部署 ECShop 开源电商系统
linux·运维·服务器·经验分享
做运维的阿瑞3 小时前
Shell 脚本经典十三问:引号、变量、子 Shell 与重定向一次讲清问:引号、变量、子 Shell 与重定向一次讲清
linux·tcp/ip
昌原的儿子LEO3 小时前
Linux IO多路复用与SQLite数据库核心知识点总结
linux·数据库·oracle
GeW3 小时前
RHCE通关秘籍:从零基础到高分拿证的5个加速器
linux
前端世界3 小时前
基于 Linux 的本地 AI 智能问答平台搭建实践 —— Ollama + FastAPI + Nginx 实现本地大模型 Web 服务
linux·运维·人工智能