zoukankan      html  css  js  c++  java
  • 双向链表快速实现一个通用队列

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

    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;       
    }
  • 相关阅读:
    WP之Sql Server CE数据库
    WP布局之Pivot和Panorama
    设计模式之职责链模式
    设计模式之命令模式
    设计模式之桥接模式
    设计模式之组合模式
    设计模式之备忘录模式
    设计模式之适配器模式
    记录参加微软打造开发者社会生态圈线下会议
    ”我的2016“-太多难忘的第一次
  • 原文地址:https://www.cnblogs.com/rayfloyd/p/11692483.html
Copyright © 2011-2022 走看看