生产者消费者模型c++

#include <iostream>
#include <condition_variable>
#include <pthread.h>
#include <thread>
#include <unistd.h>
#include <mutex>

using namespace std;


template <typename T>
class CircleQueue {
public:
    CircleQueue(int sz) : m_head(0), m_tail(0), m_max_sz(sz+1), m_cur_sz(0) {
        m_array = new T[m_max_sz];
        pthread_cond_init(&m_cv, NULL);
        pthread_mutex_init(&m_mtx, NULL);
    }
    ~CircleQueue() {
        if(m_array) {
            delete[] m_array;
        }

        pthread_mutex_destroy(&m_mtx);
        pthread_cond_destroy(&m_cv);
    
    }
    bool isFull() {
        pthread_mutex_lock(&m_mtx);
        if(m_cur_sz >= m_max_sz) {
            pthread_mutex_unlock(&m_mtx);
            return true;
        }
        pthread_mutex_unlock(&m_mtx);
        return false;
    }

    bool isEmpty() {
        pthread_mutex_lock(&m_mtx);
        if(m_cur_sz == 0) {
            pthread_mutex_unlock(&m_mtx);
            return true;
        }
        pthread_mutex_unlock(&m_mtx);
        return false;
    }

    bool push(T val) {
        pthread_mutex_lock(&m_mtx);
        if(m_cur_sz >= m_max_sz) {
            pthread_cond_broadcast(&m_cv);
            pthread_mutex_unlock(&m_mtx);
            return false; 
        }
        m_array[m_tail] = val;
        m_tail = (m_tail + 1) % m_max_sz;
        ++m_cur_sz;

        pthread_cond_broadcast(&m_cv);
        pthread_mutex_unlock(&m_mtx);
        return true;
    }

    bool pop(T& val) {
        pthread_mutex_lock(&m_mtx);
        while(m_cur_sz <= 0) {
            if(!pthread_cond_wait(&m_cv, &m_mtx)) {
                pthread_mutex_unlock(&m_mtx);
                return false;
            }
        }

        val = m_array[m_head];
        m_head = (m_head + 1) % m_max_sz;

        --m_cur_sz;
        pthread_mutex_unlock(&m_mtx);
        return true;
    }
    
private:
    pthread_cond_t m_cv;
    pthread_mutex_t m_mtx;

    T* m_array;

    int m_cur_sz;
    int m_head, m_tail, m_max_sz;
};

CircleQueue<int> cq(5);

void produce() {

    int num = 0;
    
    while(1) {
        auto ret = cq.push(num);
        if(ret) {
            cout << std::this_thread::get_id() << " : " << num << " - " << "push successfully" << endl;
            ++num;
        }
    }
}

void cosumer() {

    while(1) {
        int num = 0;
        auto ret = cq.pop(num);
        if(ret)
            cout << std::this_thread::get_id() << " : " << num << " - pop successfully" << endl;
        else 
            cout << "Empty" << endl;
    }
}



int main() {

    thread t1(produce);
    thread t3(cosumer); 


    t1.join();

    t3.join();


    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值