• 双向链表快速实现一个通用队列


    直接贴代码了,实践中也经常用到,没必要每次都自己写。

    struct queue{
        void *prev;
        void *next;
        int count;
        enum queuestate state;
        pthread_mutex_t mutex;
        pthread_cond_t cond;
    };
    //初始化
    static inline void init_queue(struct queue *q)
    {
        q->prev = q->next = q;
        q->count = 0;
        pthread_mutex_init(&q->mutex, NULL);
        pthread_cond_init(&q->cond, NULL);
    }
    
    //入队
    static inline void enqueue(struct link_list *item, struct queue *q_head)
    {
        if (item == NULL) {
            return;
        }
        pthread_mutex_lock(&q_head->mutex);
        struct link_list *q_tail = NULL;
        q_tail = q_head->prev;
    
        ((struct link_list *)item)->prev = q_tail;
        ((struct link_list *)item)->next = q_head;
        q_tail->next = item;
        q_head->prev = item;
    
        q_head->count++;
    
        pthread_cond_signal(&q_head->cond);
        pthread_mutex_unlock(&q_head->mutex);
        return;
    }
    //出队
    static inline void *dequeue(struct queue *q_head)
    {
        struct link_list *q_item = NULL, *next = NULL;
    
        pthread_mutex_lock(&q_head->mutex);
    
        while (0 == q_head->count) {
            pthread_cond_wait(&q_head->cond, &q_head->mutex);
        }
    
        q_item = q_head->next;
        next = q_item->next;
    
        q_head->next = q_item->next;
        next->prev = q_item->prev;
    
        q_head->count--;
    
        q_item->prev  = NULL;
        q_item->next = NULL;
    
        pthread_mutex_unlock(&q_head->mutex);
    
        return q_item;
    }
    struct my_msg {
        void *prev;
        void *next;
    
        char data[MAX_MSG_SIZE];
        int len;
    };
    
    int main()
    {
        struct queue mqtt_send;
        init_queue(&mqtt_send);
    
        struct my_msg *test = (struct my_msg *)malloc(sizeof(struct my_msg));
        //入队
        enqueue(&mqtt_send, test);
        //出队
        struct my_msg *newtest =  (struct my_msg *)dequeue(&mqtt_send);
        return 0;       
    }
  • 相关阅读:
    Linux防火墙:iptables禁IP与解封IP常用命令
    php7安装 event扩展
    laravel5.5 调用系统自带登陆认证auth
    linux 搭建rap记录
    微信小程序silk格式转码成mp3格式
    抓包软件
    laravel 微信小程序登录 加密解密扩展包
    mysql索引
    sphinx-for-chinese在windows下安装与使用方法
    sphinx增量索引和主索引来实现索引的实时更新
  • 原文地址:https://www.cnblogs.com/rayfloyd/p/11692483.html
Copyright © 2020-2023  润新知