How to use list from sys/queue.h?

♀尐吖头ヾ 提交于 2019-12-03 04:52:33

问题


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?


回答1:


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/



来源:https://stackoverflow.com/questions/7627099/how-to-use-list-from-sys-queue-h

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!