c - 如何使用 sys/queue.h 中的列表?

标签 c linux list bsd

目前,我已经实现了一个单向链表,像这样:

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

...我有一个结构,其中包含几个这样的链表,如下所示:

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

我想使用 sys/queue.h 提供的宏来替换它。我想我可以用这样的东西替换我的代码:

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

然后,通过查看 man queue,我相信我会通过执行以下操作来初始化列表:

LIST_INIT(&peer_list);
LIST_INIT(unchoked_peers);

但是,我不明白 LIST_ENTRY 如何影响列表的使用。在 man 页面中,它说:“宏 LIST_ENTRY 声明了一个连接列表中元素的结构,”但我真的不明白这是什么意思。

为什么我要声明一个结构来连接列表中的元素?每个节点不应该通过指针连接到下一个节点,就像我最初的链表实现一样吗?我如何用 sys/queue.h 提供的实现替换我的链表?如何将元素插入列表?

最佳答案

LIST_ENTRY 创建字段以放入适合链接元素的结构中,因此您不必关心这些指针的细节。

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

然后要创建一个列表,您将使用 LIST_HEAD():

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

您可以使用 LIST_INIT() 初始化列表头:

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

您可以使用 LIST_INSERT_*() 宏插入元素:

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

这全部取自 http://www.manpagez.com/man/3/queue/ 的手册页中的列表示例

完整示例: http://infnis.wikidot.com/list-from-sys-queue-h

关于c - 如何使用 sys/queue.h 中的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7627099/

相关文章:

linux - 来自 udev 规则的参数未传递到 perl 脚本

c - 链表 C 删除节点

C语言,对数组中的元素进行分组

linux - 在EC2上运行大数据集,担心存储

linux - 在运行时查找我的 Linux 共享库

python - "AttributeError: ' 列表 ' object has no attribute ' 整理 '"

python - 使用 python 对 beautifulsoup 标签列表进行排序

c - 中断服务例程不会跳回到 ARM Cortex M0 上的中断处理程序

C的for循环中的条件

c - `malloc()`刚刚分配的内存内容是什么?