首页 > 其他 > 详细

内核数据结构-链表

时间:2021-09-06 21:17:53      阅读:10      评论:0      收藏:0      [点我收藏+]

链表作为一种常用的数据结构,内核中使用很多,常用的链表把数据结构放入链表,定义方式如下:

struct fox {

  unsigned long tail_length;

  unsigned long weight;

  bool is_fantastic;

  struct fox *next;

  struct fox *prev;

};

这种链表的定义方式就是,等你创建一个链之后,需要自己去实现它的增删改查操作,如果有很多不同类型的链表,就需要为其重复实现增删改查。为了避免重复造轮子,内核提供了一种精妙的设计——把链表放到数据结构。

链表在<linux/list.h>中声明如下:

struct list_head {

  struct list_head *next;

  struct list_head *prev;

};

该链表实现了通用的操作比如list_add()方法。

在需要使用链表的时候,将改链表结构放到自定义的数据结构:

struct fox {

  unsigned long tail_length;

  unsigned long weight;

  bool is_fantastic;

  struct list_head list;

};

该链表的操作方法指接受list_head结构作为参数,需要找父结构中包含的变量试,可以使用container_of()宏。

#define container_of(ptr, type, member)  ({ const typeof(((type *)0) *__mptr = (ptr); (type *) ((char *)__mptr - offsetof(type, member));})

因为在C语言中,一个给定结构的变量偏移在编译时,地址就被ABI固定下来了。

内核数据结构-链表

原文:https://www.cnblogs.com/Reggie/p/15234892.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!