0

I'm trying to understand the lock-less list in the Linux kernel. This is defined in llist.h. Why do they have two structs, to define a list:

struct llist_head {
    struct llist_node *first;
};

struct llist_node {
    struct llist_node *next;
};

Why not have just one struct that has a pointer to the next node? It would similar to the doubly linked list implementation in the kernel.

user2233706
  • 6,148
  • 5
  • 44
  • 86
  • 2
    Imagine, the list is empty, e.g. there is no single `node` in it... – fukanchik Aug 03 '16 at 16:11
  • The kernel's doubly linked list implementation (non lock-less) handles empty lists without having two structs. – user2233706 Aug 03 '16 at 16:26
  • Look that field names are named differently. Think that you want to call the first element `first`, and not `next`. This prevents some errors sourced from **copy&paste** programming, as the identifiers are not valid in the _other_ context. – Luis Colorado Aug 05 '16 at 07:59

1 Answers1

0

Why do they have two structs, to define a list?

Because it is possible to use different struct (types) for different things (head and node correspondingly). Linux kernel tends to follow same convensions as for usual programming.

In case of double linked lists, both head and node are forced to have the same type: by design, both next and prev fields of struct list_head may point either to node or to the head. Single type for them is not an advantage, but necessity.

Tsyvarev
  • 60,011
  • 17
  • 110
  • 153
  • You can use `union {struct head a; struct node b;}` and make your pointer a pointer to the `union` instead.... _necessity_ can be ok for a first prototype, but in quality code you **must type differently things that are different**. – Luis Colorado Aug 05 '16 at 08:02
  • @LuisColorado, but you have to take care about union aliasing (should not to happen in your code). – 0andriy Aug 12 '16 at 16:51