代码改变世界

生产者消费者原理性的实现

2013-05-20 17:26  夏洛克·福尔摩斯  阅读(250)  评论(0编辑  收藏  举报

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