|
|
Log in / Subscribe / Register

My linked lists

My linked lists

Posted Mar 10, 2022 16:15 UTC (Thu) by abatters (✭ supporter ✭, #6932)
Parent article: Toward a better list iterator for the kernel

For non-circular linked lists in my userspace code, my approach is to define a dedicated macro for each specific list, defining the name of its head, tail, forward, and back pointers. Then that specific macro can be used in combination with one of ~25 generic doubly-linked list macros I have defined. Works well for having a single object in multiple lists, and having multiple lists in a single container. No iteration macro is necessary, since you have pointers to the real types (no container_of needed) and it terminates with NULL.

// Generic doubly-linked list macro (one of ~25)
#define DLIST_ADD_TAIL(head, tail, forw, back, item) \
   do { \
      if ((tail) == NULL) { \
         (head) = (item); \
      } else { \
         (item)->back = (tail); \
         (tail)->forw = (item); \
      } \
      (tail) = (item); \
   } while (0)

// Example linked list structs
struct item {
  struct item *iforw, *iback;
};
struct container {
  struct item *ihead, *itail;
};

// Example macro defining a specific list
#define CONTAINER_ITEM_LIST(container, func, args...) \
  func((container)->ihead, (container)->itail, iforw, iback , ## args)

void container_add_item_tail(struct container *container, struct *item)
{
   CONTAINER_ITEM_LIST(container, DLIST_ADD_TAIL, item);
}


to post comments


Copyright © 2026, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds