转:一文读懂list_head相关

1.list_entry的作用

struct list_head {
  struct list_head *next, *prev;
};

没有数据区怎么使用,更多的时候是嵌入到其他结构体中使用。

struct file_node{
  char c;
  struct list_head node;
};

当我们知道 list_head的地址时,就可以通过宏 list_entry获取父结构的地址:

#define list_entry(ptr,type,member)
  container_of(ptr,type,member)

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

#define offsetof(TYPE,MEMBER) ((size_t)&((TYPE *)0)->MEMBER)

首先解释offsetof:
将实参代入 offset( struct file_node, node )
( (size_t) & ((struct file_node*)0)-> node )

这句的意思是将结构体file_node的指针转变为0,那么node的指针就是相对于0d地址的指针,即node在file_node中的偏移。

然后解释 container_of :
该句有两句组成:
首先第一句可以缩减为:_mtr = (ptr)即保存 ptr的指针。
第二句: _mptr - 该member相对于结构体的偏移,那么得到的不就是父结构体的指针了么。

扫描二维码关注公众号,回复: 3678810 查看本文章

所以 list_entry的作用就是得到父结构的起始地址。

2.LIST_HEAD()

LIST_HEAD就是定义一个前向和后向都指向自己的list_head

#define LIST_HEAD(name)
struct list_head name = LIST_HEAD_INIT(name)

#define LIST_HEAD_INIT(name) { &(name), &(name) }
INIT_LIST_HEAD就是指向初始化一个list_head指向实际的结构体

static inline void INIT_LIST_HEAD(struct list_head *list)
{
  list->next = list;
  list->prev = list;
}

双向链表的插入操作 – list_add()

将new所代表的结构体插入head所管理的双向链表的头节点head之后: (即插入表头)

static inline void list_add(struct list_head *new, struct list_head *head)
{
  __list_add(new, head, head->next);
}
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; //之前的前边的后向指向新的
}

双向链表的插入操作 – list_add_tail()

将new所代表的list_head插入head所索引的队列的尾部:

static inline void list_add_tail(struct list_head *new, struct list_head *head)
{
    __list_add(new, head->prev, head);
}

从list中删除结点——list_del()

static inline void list_del(struct list_head *entry)
{
  __list_del(entry->prev, entry->next);
  entry->next = LIST_POISON1;
  entry->prev = LIST_POISON2;
}
static inline void __list_del(struct list_head * prev, struct list_head * next)
{
  next->prev = prev;
  prev->next = next;
}

判断链表是否为空(如果双向链表head为空则返回真,否则为假)——list_empty()

static inline int list_empty(const struct list_head *head)
{
  return head->next == head;
}

3.list_for_each_entry

/**
* list_for_each_entry - iterate over list of given type
* @pos: the type * to use as a loop cursor.
* @head: the head for your list.
* @member: the name of the list_struct within the struct.
*/

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

猜你喜欢

转载自blog.csdn.net/lidong0805/article/details/83185460