#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;
}
#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;
}

443

被折叠的 条评论
为什么被折叠?



