代码之家  ›  专栏  ›  技术社区  ›  ng.newbie

为什么内核中大多数链表循环宏都跳过第一个元素?

  •  1
  • ng.newbie  · 技术社区  · 5 年前

    <linux/list.h> list_for_each_entry_safe 从第二个元素开始:

    #define list_for_each_entry_safe(pos, n, head, member)          \
        for (pos = list_entry((head)->next, typeof(*pos), member),  \
            n = list_entry(pos->member.next, typeof(*pos), member); \
             &pos->member != (head);                    \
             pos = n, n = list_entry(n->member.next, typeof(*n), member))
    

    请注意,循环以 pos = list_entry((head)->next .

    我知道这听起来可能有点吹毛求疵,但用一种“真正”的方式,就像用Python一样

    在内核中违反这个约定有什么特别的原因吗? 是因为性能原因吗?

    还是我对上述代码的理解完全错误?

    0 回复  |  直到 5 年前
        1
  •  3
  •   Marco Bonelli    5 年前

    head 是一个 第一元素 在名单上。以及 head->next

    例如,下面是宏的定义,它返回列表的第一个条目:

    #define list_first_entry(ptr, type, member) \
        list_entry((ptr)->next, type, member)
    
        2
  •  3
  •   caf    5 年前

    侵入式数据结构 ,其中列表元素结构包含在列表的数据元素中,而不是包含列表元素中的数据元素(或指向它们的指针)的外部列表。

    但是,列表的第一个(head)元素不包含在数据元素中。相反,它包含在拥有该列表的数据结构中(可能与数据元素的类型不同)。这意味着在遍历列表的数据元素时,不包含列表头(因为它根本不包含在数据元素中)。

    例如, struct device (定义见 linux/device.h )包含一个字段 struct list_head msi_list; . 这是一份 struct msi_desc linux/msi.h ),和 结构msi\ U desc 包含相应的字段 struct list_head list; . MSI描述符的列表由 struct list_head 元素,但head元素是 msi_list a的字段 结构体 ,而其他元素则各不相同 list a的要素 . 在遍历列表时,我们只想遍历 结构msi\ U desc 数据元素(我们已经有了 结构体 -这就是为什么我们一开始就得到了榜首)。