Linux内核中list_for_each()和list_for_each_safe()
今天看Linux内核代码,看到了list_for_each_safe()函数,想仔细的研究一下。
下面是源代码:
list_for_each()的定义:
/** * list_for_each - iterate over a list * @pos: the &struct list_head to use as a loop cursor. * @head: the head for your list. */ #define list_for_each(pos, head) for (pos = (head)->next; pos != (head); pos = pos->next)
list_for_each_safe()的定义:
/** * list_for_each_safe - iterate over a list safe against removal of list entry * @pos: the &struct list_head to use as a loop cursor. * @n: another &struct list_head to use as temporary storage * @head: the head for your list. */ #define list_for_each_safe(pos, n, head) for (pos = (head)->next, n = pos->next; pos != (head); pos = n, n = pos->next)
下面主要是介绍一下他们的区别:
我们指导在遍历一个双向链表list的时候有可能会删除其中的元素,这就有可能出现问题。我们首先看一下删除链表元素的
函数,函数如下:(注意:这里我们队Linux内核函数中设计的宏定义等进行了展开)
static inline void list_del(struct list_head *entry)
{
entry->next->prev=entry->prev;
entry->prev->next=entry->next;
entry->next = LIST_POISON1;
entry->prev = LIST_POISON2;
}
这里先说一下下面两行代码:
entry->next = LIST_POISON1; entry->prev = LIST_POISON2;
删除元素过程见下图:
删除前:
删除后:
当我们采用list__for_each()函数遍历list时,如果我们删除元素,就会导致pos指向的元素的prev=LIST_POISON1,next=LIST_POISON2,当执行到pos=pos->next时,就会出现错误。
但是当我们使用list_for_each_safe()函数遍历list时,如果我们也删除元素后,会执行pos=n,而n=pos->next,注意:n=pos->next中的pos是删除的那个元素,所以虽然删除了元素pos,但是执行了pos=n后,pos指向了正确的遍历位置,所以使用list_for_each_safe()函数遍历list时并不会出现错误。list_for_each_safe()在遍历时之所以不会出现错误,是因为我们使用了n暂时保存了pos,也就是被删除元素所指向的下一个元素,所以用这个函数,准确来说是宏定义,不会出现遍历时删除元素的错误。
