Linux内核中list_for_each()和list_for_each_save()

Linux内核中list_for_each()和list_for_each_save()

2018年08月22日 21:24:54 ibless 阅读数:41

注:彩色文本是转发者修改过,个人理解不一定正确,请多指教!。

今天看Linux内核代码,看到了list_for_each_save()函数,想仔细的研究一下。

下面是源代码:

list_for_each()的定义:

 
  1. /**

  2. * list_for_each - iterate over a list

  3. * @pos: the &struct list_head to use as a loop cursor.

  4. * @head: the head for your list.

  5. */

  6. #define list_for_each(pos, head) for (pos = (head)->next; pos != (head); pos = pos->next)

list_for_each_save()的定义:

 
  1. /**

  2. * list_for_each_safe - iterate over a list safe against removal of list entry

  3. * @pos: the &struct list_head to use as a loop cursor.

  4. * @n: another &struct list_head to use as temporary storage

  5. * @head: the head for your list.

  6. */

  7. #define list_for_each_safe(pos, n, head) \

  8. for (pos = (head)->next, n = pos->next; pos != (head); \

  9. pos = n, n = pos->next)

下面主要是介绍一下他们的区别:

    我们指导在遍历一个双向链表list的时候有可能会删除其中的元素,这就有可能出现问题。我们首先看一下删除链表元素的

函数,函数如下:(注意:这里我们队Linux内核函数中设计的宏定义等进行了展开)

 
  1. static inline void list_del(struct list_head *entry)

  2. {

  3. entry->next->prev=entry->prev;

  4. entry->prev->next=entry->next;

  5. entry->next = LIST_POISON1;

  6. entry->prev = LIST_POISON2;

  7. }

这里先说一下下面两行代码:

 
  1. entry->next = LIST_POISON1;

  2. entry->prev = LIST_POISON2;

 
  1. 下面是LIST_POISON1和LIST_POISON2的出处:

  2. #ifdef CONFIG_ILLEGAL_POINTER_VALUE

  3. # define POISON_POINTER_DELTA _AC(CONFIG_ILLEGAL_POINTER_VALUE, UL)

  4. #else

  5. # define POISON_POINTER_DELTA 0

  6. #endif

  7. /*通常情况下,非空指针会导致页错误,用于验证没有初始化的list元素。

  8. * These are non-NULL pointers that will result in page faults

  9. * under normal circumstances, used to verify that nobody uses

  10. * non-initialized list entries.

  11. */

  12. #define LIST_POISON1 ((void *) 0x100 + POISON_POINTER_DELTA)

  13. #define LIST_POISON2 ((void *) 0x200 + POISON_POINTER_DELTA)

删除元素过程见下图:

删除前:

删除后:

当我们采用list__for_each()函数遍历list时,如果我们删除元素,就会导致pos指向的元素的prev=LIST_POISON1,next=LIST_POISON2,(删除pos元素后,此时pos指针指向的节点就不是本链表的节点了,指到了别的地方,如果下一次循环调用pos增量时,不会指向删除前pos的后一个节点的位置了,所以此代码应该不能用,)当执行到pos=pos->next时,就会出现错误。(list_for_each()真的不能使用吗?若能使用又是为什么?)

但是当我们使用list_for_each_save()函数遍历list时,如果我们也删除元素后,会执行pos=n,而n=pos->next,注意:n=pos->next中的pos是删除的那个元素,所以虽然删除了元素pos,但是执行了pos=n后,pos指向了正确的遍历位置,所以使用list_for_each_save()函数遍历list时并不会出现错误。list_for_each_save()在遍历时之所以不会出现错误,是因为我们使用了n暂时保存了pos,也就是被删除元素所指向的下一个元素,所以用这个函数,准确来说是宏定义,不会出现遍历时删除元素的错误。

猜你喜欢

转载自blog.csdn.net/weixin_41632560/article/details/86306145
今日推荐