C 宏实现队列

http://trac.openrays.org/projects/pmon/browser/trunk/sys/sys/queue.h?rev=2

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是我自己用 C 语言实现的 Linux 内核队列,按照 Linux 内核代码风格: ```c #include <stdio.h> #include <stdlib.h> struct list_head { struct list_head *prev, *next; }; #define LIST_HEAD_INIT(name) { &(name), &(name) } #define LIST_HEAD(name) struct list_head name = LIST_HEAD_INIT(name) static inline void INIT_LIST_HEAD(struct list_head *list) { list->next = list; list->prev = list; } static inline void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next) { new->prev = prev; new->next = next; prev->next = new; next->prev = new; } static inline void list_add(struct list_head *new, struct list_head *head) { __list_add(new, head, head->next); } static inline void list_add_tail(struct list_head *new, struct list_head *head) { __list_add(new, head->prev, head); } static inline void __list_del(struct list_head *prev, struct list_head *next) { prev->next = next; next->prev = prev; } static inline void list_del(struct list_head *entry) { __list_del(entry->prev, entry->next); entry->next = NULL; entry->prev = NULL; } static inline int list_empty(struct list_head *head) { return head->next == head; } #define offsetof(type, member) ((size_t) &((type *)0)->member) #define container_of(ptr, type, member) ({ \ const typeof(((type *)0)->member) *__mptr = (ptr); \ (type *)((char *)__mptr - offsetof(type, member)); }) struct my_node { int value; struct list_head list; }; LIST_HEAD(my_queue); void enqueue(int value) { struct my_node *node = malloc(sizeof(*node)); node->value = value; INIT_LIST_HEAD(&node->list); list_add_tail(&node->list, &my_queue); } int dequeue(void) { if(list_empty(&my_queue)) { printf("queue is empty\n"); return -1; } struct my_node *node = container_of(my_queue.next, struct my_node, list); int value = node->value; list_del(&node->list); free(node); return value; } int main(void) { int i; // 入队 for(i = 0; i < 5; i++) { enqueue(i); } // 出队 int value; while((value = dequeue()) != -1) { printf("dequeue value: %d\n", value); } return 0; } ``` 这份代码实现了一个简单的队列,采用双向链表来存储元素。和之前的链表实现相似,这份代码也增加了一些定义和内联函数,以及`offsetof`和`container_of`两个队列实现和链表略有不同,入队操作使用`list_add_tail`函数,将元素添加到链表末尾。出队操作则从链表头部取出元素,并使用`list_del`函数将其删除。 需要注意的是,这份代码只是一个简单的队列实现,没有考虑线程安全等问题。在实际应用中,可能需要添加锁或者使用队列库来避免竞争条件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值