生产者消费者问题

题目:有生产者在生产产品,这些产品将提供给若干个消费者去消费,为了使生产者和消费者能并发执行,在两者之间设置一个有多个缓冲区的缓冲池,生产者将它生产的产品放入一个缓冲区中,消费者可以从缓冲区中取走产品进行消费,所有生产者和消费者都是异步方式运行的,但它们必须保持同步,即不允许消费者到一个空的缓冲区中取产品,也不允许生产者向一个已经装满产品且尚未被取走的缓冲区中投放产品。

假设条件:

1.有5个生产者,每1s生产1件商品

2.有5个消费者,每1s消费1件商品

3.缓冲池大小为5

4.生产者一共生产100件商品后结束

#include <iostream>
#include <thread>
#include <mutex>
#include <deque>
#include <vector>
#include <condition_variable>

using namespace std;

class CThreadDemo
{
private:
    std::deque<int> m_data;
    std::mutex m_mtx; // 全局互斥锁.
    std::condition_variable m_cv; // 全局条件变量.
    int   m_nGen;

private:
    void ProductThread(){
        while (true){
            std::unique_lock <std::mutex> lck(m_mtx);
            m_nGen = ++m_nGen;
            while(m_data.size() >=5) {
            m_cv.wait(lck);
        }
        if(m_nGen > 100){
            break;
        }
        cout << "p :" << m_nGen << endl;
        m_data.push_back(m_nGen);
        lck.unlock();
        m_cv.notify_all();  
        // 等待1S 
       std::chrono::milliseconds dura(1000);
       std::this_thread::sleep_for(dura);
       }
    }

    void ConsumeThread(){
        while (true){
            std::unique_lock <std::mutex> lck(m_mtx);
            if(m_nGen > 100){
                break;
            }
            while (m_data.empty()){
                m_cv.wait(lck);
            }
            int nData = m_data.front();
            m_data.pop_front();
            cout << "c :" << nData << endl;
            lck.unlock();
                        
            std::chrono::milliseconds dura(15000);
            std::this_thread::sleep_for(dura);
        }
   }
public:
    CThreadDemo(){
        m_data.clear();
        m_nGen = 0;
    }

    void Start(){
        std::vector<std::thread> threads;
        threads.clear();
        for (int i = 0; i < 5; i++){// 生产者线程 
            threads.push_back(std::thread(&CThreadDemo::ProductThread, this));
        }
        for (int i = 5; i < 10; i++){// 消费者线程 
            threads.push_back(std::thread(&CThreadDemo::ConsumeThread, this));
        }
        for (auto& t : threads){// 等待所有线程的退出 
            t.join();
        }
   }
};


int main(int argc, char **argv)
{
    CThreadDemo test;
    test.Start();
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值