C++基础-消费者和生产者模式

消费者和生产者模式

1.生产者,在数量少于10的时候,不断生产,并且通知消费者,开始消费, 等于10的时候,加锁进行等待

2.消费者, 在数量大于0的时候,不断消费,并且通知生产者,开始生产,等于0的时候,加锁进行等待

//
// Created by Administrator on 2021/7/7.
//
#include<iostream>
#include<thread>
#include<mutex>
#include<condition_variable>
#include<array>
#include<vector>

using namespace std;

mutex m;
condition_variable isfull, isempty; //处理两种情况
bool flag = true; //标志,消费完就退出
vector<int> myint; //开辟10个元素

//100.生产者

void put(int num)
{
    for(int i = 0; i < num; i++)
    {
        unique_lock<mutex>lk(m); //锁定状态
        while(myint.size()>=10){
            isempty.wait(lk); //满了一直等待
        }
        myint.push_back(i); //插入
        cout << "生产" << i << endl;
        isfull.notify_all(); //通知消费者
    }
    this_thread::sleep_for(chrono::seconds(5)); //休眠
    flag = false;
}

void take()
{
    while(flag)
    {
        unique_lock<mutex>lk(m); //锁定状态
        while(myint.size() == 0){
            isfull.wait(lk); //等待
        }
        if(flag){
            cout << "消费" <<myint[myint.size()-1] << " " << this_thread::get_id() << endl;
            myint.pop_back(); //把最后一个消除
            isempty.notify_all(); //通知生产者继续生产
        }

    }
}

int main()
{
    thread t1(take);
    thread t2(take);
    thread t3(take);
    thread s1(put,50);
    thread s2(put, 50);
//    put(100);
    t1.join();
    t2.join();
    t3.join();
    s1.join();
    s2.join();

}
原文地址:https://www.cnblogs.com/my-love-is-python/p/14984244.html