Categories
bsd c linux list

How to use list from sys/queue.h?

Currently, I have implemented a singly linked list, like so:

struct PeerNode {
struct Peer* cargo;
struct PeerNode* next;
};

…and I have a struct that contains a couple of these linked lists, like so:

struct Torrent {
...
struct PeerNode* peer_list;
struct PeerNode* unchoked_peers;
...
}

I would like to replace this by using the macros provided by sys/queue.h. I gather that I could replace my code with something like this:

struct Torrent {
...
LIST_ENTRY(PeerNode, Peer) peer_list;
struct PeerNode* unchoked_peers;
...
}

Then, from looking at man queue, I believe I would initialize the lists by doing something like this:

LIST_INIT(&peer_list);
LIST_INIT(unchoked_peers);

However, I don’t understand how LIST_ENTRY factors into usage of the list. From the man page, it says: “The macro LIST_ENTRY declares a structure that connects the elements in the list,” but I don’t really understand what this means.

Why would I want to declare a structure to connect the elements in the list? Shouldn’t each node be connected to the next node via a pointer, like my initial linked list implementation? How would I replace my linked lists with the implementation provided by sys/queue.h? How would I insert an element into the list?

LIST_ENTRY creates fields to put into your structure that are suitable for linking the elements, so you do not have to concern yourself with the specifics of those pointers.

struct foo {
int a, b, c;
/* This is instead of "struct foo *next" */
LIST_ENTRY(foo) pointers;
};

To then create a list you’d use LIST_HEAD():

struct Torrent {
LIST_HEAD(foo_list, foo) bar;
};

You can initialise the list header using LIST_INIT():

struct Torrent t;
LIST_INIT(&t.bar);

You can insert elements using the LIST_INSERT_*() macros:

struct foo *item = malloc(sizeof(struct foo));
LIST_INSERT_HEAD(&t.bar, item, pointers);

This was all taken from the list example in the man pages at http://www.manpagez.com/man/3/queue/

For a full example:
http://infnis.wikidot.com/list-from-sys-queue-h