生产者消费者

#include<stdio.h>
#include <iostream>
#include<windows.h>
#include <string>
#include<stdlib.h>
#include<time.h>
using namespace std;
#define error -1
const int n=10;
int in,out,cnt=0,mutex=1;
int buffer[n];
bool g_continue = true; 
void menu()
{
cout<<"生产或消费"<<endl;
cout<<"1.生产操作"<<endl;
cout<<"2.消费操作"<<endl;
}


void Producer()
{


if(mutex==0)
cout<<"缓冲池正在被使用,请稍后!"<<endl;
while(mutex)
{
if(cnt==n)
{
cout<<"缓冲池已满,生产请等待!"<<'\n';
Sleep(4000);
return ;
}
else
{
srand( (unsigned)time( 0 ) );
in=(in+1)%n;
    buffer[in]=rand()%100+1;
cout<<"生产操作:"<<'\n'<<"生产成功,此次生产产品为:"<<buffer[in]<<'\n'<<endl;
cnt++;

}
Sleep(3000);
mutex=0;
}


}
void Consumer()
{
int nextc;
if(mutex==0)
cout<<"缓冲池正在被使用,请稍后!"<<endl;
while(mutex)
{
if(cnt==0)
{
cout<<"消费操作:"<<'\n'<<"缓冲池为空,消费请等待"<<'\n'<<endl;
Sleep(4000);
return ;
}
else
{
out=(out+1)%n;
nextc=buffer[out];
cout<<"消费操作:"<<'\n'<<"消费成功,消费产品为:"<<nextc<<'\n'<<endl;
cnt--;

}
Sleep(3000);
mutex=0;
}


}


int main()
{
int k;
menu();
while(g_continue)
{
srand( (int)time( 0 ) ); 
k=1+rand()%2;
if(k==1)
Producer();
else if(k==2)
Consumer();
mutex=1;
}
getchar();
return 1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值