#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
static int s=1;
//產生指定范圍的整數隨機數
int getrand(int min,int max) {
int m;
m=(max-min);
m=min+double(rand())/RAND_MAX*m ;
return m;
}
int P(int &s)//wait(s) operator
{
return(--s);
}
int V(int &s)//singal(s) operator
{
return(++s);
}
void pro_A(int &s)//Process A
{
void pro_B(int &);
void pro_C(int &);
int i;
cout<<"S="<<s<<endl;
i=P(s);
if(i==0)
{ cout<<" A visits the critical scource...; Others must wait!!"<<endl;
switch(getrand(0,100)%2+1)
{
case 1: pro_B(i); pro_C(i); break;
case 2:pro_C(i);pro_B(i);break;
}
cout<<" A had ended!The CS is free now:"<<endl;
}
else cout<<" The CS is being used...; A must wait!"<<endl;
s=V(i);
}
void pro_B(int &s)//Process B
{
void pro_C(int &);
int i;
cout<<"S="<<s<<endl;
i=P(s);
if(i==0)
{ cout<<" B visits the critical scource...; Others must wait!!"<<endl;
switch(getrand(0,100)%2+1)
{
case 1: pro_C(i); pro_A(i);break;
case 2: pro_A(i);pro_C(i);break;
}
cout<<" B had ended!The CS is free now:"<<endl;
}
else cout<<" The CS is being used...; B must wait!"<<endl;
s=V(i);
}
void pro_C(int &s)//Process C
{
int i;
cout<<"S="<<s<<endl;
i=P(s);
if(i==0)
{ cout<<" C visits the critical scource...; Others must wait!!"<<endl;
switch(getrand(0,100)%2+1)
{
case 1: pro_A(i); pro_B(i);break;
case 2: pro_B(i); pro_A(i);break;
}
cout<<" C had ended!The CS is free now:"<<endl;
}
else cout<<" The CS is being used...; C must wait!"<<endl;
s=V(i);
}
void main()
{
char ch;
//clrscr();//Clear Screen
while(1)//CIRCLE
{
switch(getrand(0,100)%3+1)//Make a random number
{
case 1: pro_A(s);cout<<endl;break;
case 2: pro_B(s);cout<<endl;break;
case 3: pro_C(s);cout<<endl;break;
}
cout<<"Continue...(y/n)?"<<endl;
cin>>ch;
cout<<endl;
if(ch=='N'||ch=='n')
break;
}
}