多线程队列模型

时间:2019-06-05 22:40:15   收藏:0   阅读:66
template <typename T>
class Queue
{
private:
    std::queue<T> q;
    pthread_mutex_t q_mutex;
    pthread_cond_t q_cond;

public:
    Queue()
    {
        pthread_mutex_init(&q_mutex, NULL);
        pthread_cond_init(&q_cond, NULL);
    }
    virtual ~Queue()
    {
        pthread_mutex_destroy(&q_mutex);
        pthread_cond_destroy(&q_cond);
    }
    
    // 插入
    void insert(const T& e)
    {
        pthread_mutex_lock(&q_mutex);
        q.push(e);
        pthread_cond_signal(&q_cond);
        pthread_mutex_unlock(&q_mutex);
    }
    
    // 取数据,队列空则阻塞
    void take(T& e)
    {
        pthread_mutex_lock(&q_mutex);
        while(q.empty())
        {
            pthread_cond_wait(&q_cond, &q_mutex)
        }
        e = q.front();
        q.pop();
        pthread_mutex_unlock(&q_mutex);
    }
    
    // 取数据,队列空则返回
    bool pull(T& e)
    {
        boot ret = false;
        pthread_mutex_lock(&q_mutex);
        while(!q.empty())
        {
            e = q.front();
            q.pop();
            ret = true;
        }
        pthread_mutex_unlock(&q_mutex);
        return ret;
    }
};

 

原文:https://www.cnblogs.com/share-ideas/p/10981785.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!