本文介绍了linux/list.h-如何安全地从列表中删除项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

linux/list的注释中.h 写道:

  1. 在使用 list_del_entry 时:注意:条目上的 list_empty 在此之后不返回true,条目处于未定义状态.
  2. 对于 list_del :这仅用于内部列表操作,在此我们已经知道上一个/下一个条目!
  1. On using list_del_entry: Note: list_empty on entry does not return true after this, the entry is in an undefined state.
  2. For list_del: This is only for internal list manipulation where we know the prev/next entries already!

那么,我该如何安全地从链接列表中删除一个对象并确保 list_empty 正常工作,或确保下一个链接列表节点删除是正确的?

So, how would I safely remove an object from linked list and make sure that list_empty is functional or make sure that next linked list node deletion is correct?

这是我目前的实现方式

struct kool_list{
    int to;
    struct list_head list;
    int from;
};

struct kool_list *tmp;
struct list_head *pos, *q;
struct kool_list mylist;

list_for_each_safe(pos, q, &mylist.list){
         tmp= list_entry(pos, struct kool_list, list);
         printf("freeing item to= %d from= %d\n", tmp->to, tmp->from);
         list_del(pos);
         free(tmp);
}

推荐答案

我认为您误解了这些评论.第一个说 list_empty(& entry-> list)不会返回true.但是,如果从列表中删除所有元素(正确的方法)并执行 list_empty(& mylist.list),结果将为真.

I think you misunderstand the comments. The first one says that list_empty(&entry->list) will not return true. However, if you remove all elements from the list (the way you do it is correct) and do list_empty(&mylist.list) you will get true as a result.

如果出于某种原因您希望将条目的 struct list_head 保持在内部一致的状态,请使用 list_del_init .

If for some reason you want to keep the entry's struct list_head in an internally consistent state, use list_del_init.

第二, __ list_del 仅供内部使用, list_del 是公平的游戏.

Secondly, __list_del is for internal usage only, list_del is fair game.

这篇关于linux/list.h-如何安全地从列表中删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 04:48