zoukankan      html  css  js  c++  java
  • 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();
    
    }
  • 相关阅读:
    格式刷的一小步,原型工具的一大步
    精益设计,敏捷开发,一个都不能少
    慢工出细活,Facebook点赞按钮设计中的门道
    5个范例告诉你什么是自适应网页设计
    用户体验设计5大目标
    poj1251Jungle Roads(最小生成树)
    hdu2222Keywords Search
    hdu2328Corporate Identity
    hdu1238Substrings
    hdu4763Theme Section
  • 原文地址:https://www.cnblogs.com/my-love-is-python/p/14984244.html
Copyright © 2011-2022 走看看