zoukankan      html  css  js  c++  java
  • 生产者消费者原理性的实现

    #include<iostream>
    using namespace std;

    //定义缓冲区的数目
    #define N 10

    //定义互斥信号量
    int mutex=1;
    //资源信号量
    int empty=N,full=0;
    //定义缓冲区
    int ArrayOut[N],ArrayIn[N];
    //定义in ,out
    int in=0;

    //声明两个函数:Proceducer,Consumer
    void Proceducer();
    void Consumer();


    int main()
    {
    Proceducer();
    //Consumer();
    return 0;
    }

    void Proceducer()
    {
    int i=0,k;
    if(empty<=0)
    {
    cout<<"仓库已满,不能继续生产!"<<endl;
    }
    else
    {
    do
    {
    empty-=1;
    if(mutex==0)
    {
    cout<<"正在输出,暂时不能生产!"<<endl;
    }
    else
    {
    mutex=0;

    cout<<"输入第"<<in<<"缓冲区的值"<<endl;
    cin>>ArrayIn[in];
    ArrayOut[in]=ArrayIn[in];
    in=in+1;
    full++;
    if(empty<=0)
    {
    cout<<"仓库已满,不能继续生产!"<<endl;
    cout<<"是否进行消费?(1:是,0:否)"<<endl;
    cin>>k;
    if(k==0)
    break;
    else
    {
    mutex=1;
    Consumer();
    }
    }
    mutex=1;

    }
    cout<<"请选择继续生产,还是想要消费(0:生产 1:消费)"<<endl;
    cin>>i;
    }while(i==0);

    if(i==1)
    {
    mutex=1;
    Consumer();
    }

    }
    }
    void Consumer()
    {
    int j=0,k;
    if(full<=0)
    {
    cout<<"仓库为空,不能使用..."<<endl;
    }
    else
    {
    do
    {
    full-=1;

    if(mutex==0)
    {
    cout<<"正在生产,暂时不能消费!"<<endl;
    }
    else
    {
    mutex=0;
    in=in-1;
    cout<<"输出第"<<in<<"缓冲区的值"<<endl;
    cout<<ArrayOut[in]<<endl;

    if(full<=0)
    {
    cout<<"仓库为空,不能继续消费!"<<endl;
    cout<<"是否进行生产?(1:是,0:否)"<<endl;
    cin>>k;
    if(k==0)
    exit(0);
    else
    {
    mutex=1;
    Proceducer();
    }
    }

    mutex=1;
    empty++;

    }

    cout<<"请选择继续生产,还是想要消费(0:生产 1:消费)"<<endl;
    cin>>j;
    }while(j==1);

    if(j==0)
    {
    mutex=1;
    Proceducer();
    }
    }
    }

  • 相关阅读:
    Day01-基础加强笔记
    CS Academy Round#2 E.Matrix Coloring
    AtCoder ABC198 F
    NERC2021 B. Button Lock
    AtCoder ARC115 E
    NOI Online 2021 Round 1 提高组 愤怒的小 N
    洛谷 P6918 [ICPC2016 WF]Branch Assignment
    AtCoder ARC076 F
    Atcoder ABC155 F
    POJ 1966 Cable TV Network
  • 原文地址:https://www.cnblogs.com/sherlockhomles/p/3088980.html
Copyright © 2011-2022 走看看