list_for_each_entry_safe 简介

list_for_each_entry_safe 是 Linux 内核中用于遍历链表的一个宏,特别适用于在遍历过程中可能需要删除链表节点的场景。它的设计保证了在删除当前节点时,不会影响后续节点的访问,从而实现安全的遍历。

定义

c 复制代码
#define list_for_each_entry_safe(pos, n, head, member) \
    for (pos = list_entry((head)->next, typeof(*pos), member), \
         n = list_entry(pos->member.next, typeof(*pos), member); \
         &pos->member != (head); \
         pos = n, n = list_entry(n->member.next, typeof(*n), member))

参数说明

  1. pos: 当前遍历到的链表节点对应的结构体指针。
  2. n: 临时指针,用于保存下一个节点的位置。
  3. head: 链表头节点的地址。
  4. member: 链表节点在结构体中的成员名。

工作原理

  • list_for_each_entry_safe 在每次循环中,使用 n 保存当前节点的下一个节点地址。
  • 即使在循环中删除了当前节点(由 pos 指向),由于 n 已经保存了下一个节点的位置,后续遍历可以继续进行而不受影响。

使用场景

主要用于需要在遍历链表的同时删除链表节点的场景。例如:

示例代码:遍历并删除链表节点

c 复制代码
struct my_list {
    int data;
    struct list_head list;
};

struct my_list *pos, *tmp;

// 遍历并删除链表中的所有节点
list_for_each_entry_safe(pos, tmp, &head, list) {
    printk(KERN_INFO "Data: %d\n", pos->data);
    list_del(&pos->list); // 从链表中删除当前节点
    kfree(pos);           // 释放内存
}

示例代码:只遍历链表

如果只是遍历而不删除,可以使用 list_for_each_entry

c 复制代码
struct my_list *pos;

// 遍历链表
list_for_each_entry(pos, &head, list) {
    printk(KERN_INFO "Data: %d\n", pos->data);
}

list_for_each_entry 的区别

  • list_for_each_entry: 用于普通遍历,不支持安全删除操作。
  • list_for_each_entry_safe: 在遍历过程中允许安全地删除当前节点。

总结

list_for_each_entry_safe 是 Linux 内核中处理双向链表的一种高级工具,适合需要在遍历过程中修改或删除链表元素的场景。它通过额外的临时指针确保操作安全,不会破坏链表结构[1][2][3].

Citations:

1\] https://developer.aliyun.com/article/375545 \[2\] https://blog.csdn.net/Wang20122013/article/details/112307416 \[3\] http://www.korantli.com.cn/linux/nei-he-lian-biao/ \[4\] https://www.cnblogs.com/yangguang-it/p/11667772.html \[5\] https://blog.csdn.net/weixin_42645653/article/details/126560076 \[6\] https://www.cnblogs.com/zhoug2020/p/4972923.html \[7\] https://www.51cto.com/article/695735.html \[8\] https://juejin.cn/post/7091220406312370213

相关推荐
武藤一雄3 小时前
C# 关于多线程如何实现需要注意的问题(持续更新)
windows·后端·microsoft·c#·.net·.netcore·死锁
kaikaile19956 小时前
基于拥挤距离的多目标粒子群优化算法(MO-PSO-CD)详解
数据结构·算法
不忘不弃6 小时前
求两组数的平均值
数据结构·算法
leaves falling6 小时前
迭代实现 斐波那契数列
数据结构·算法
DonnyCoy6 小时前
Android性能之数据结构
数据结构
天赐学c语言6 小时前
1.7 - 删除排序链表中的重要元素II && 哈希冲突常用解决冲突方法
数据结构·c++·链表·哈希算法·leecode
coding消烦员7 小时前
在 Windows 内网搭建 Git 仓库:共享普通仓库 vs 中心 bare 仓库
windows·git
菜鸟233号7 小时前
力扣96 不同的二叉搜索树 java实现
java·数据结构·算法·leetcode
空空潍8 小时前
hot100-最小覆盖字串(day12)
数据结构·算法·leetcode
yyy(十一月限定版)8 小时前
算法——二分
数据结构·算法