/*********************************************************************************
By => Ajit Medhekar... Xtream Kings... K.K.Wagh COE,Nashik...
Ajit's Blog :- http://ammedhekar.blogspot.com
*********************************************************************************/
#include<stdio.h>
#include<conio.h>
#include<iostream.h>
#include<stdlib.h>
//status:1=eating,status:0:thinking
class semaphore
{
public:
int s;
semaphore()
{
s=1;
}
int wait()
{
int s1;
s1=s;
s1--;
if(s1<0)
{
cout<<"\nblock";
return(1);
}
else
{
s--;
cout<<"\nWait:"<<s;
return(0);
}
}
void signal()
{ int s1;
s1=s;
s1++;
if(s1<=0)
{
cout<<"\nblocked philosophers can eat now";
}
else
{
s++;
cout<<"\nsignal:"<<s;
}
}
};
void main()
{
int ch,phil,status[10],i,block1,block2;
semaphore chopstik[5];
clrscr();
for(i=1;i<=5;i++)
{
status[i]=0; //thinking
}
do
{
cout<<"\n1.eat\n2.think\n3.status\n4.Allowed philosophers for eating\n5.exit";
cout<<"\nEnter choice:";
cin>>ch;
switch(ch)
{
case 1:
cout<<"\nEnter the philosopher who wants to eat:";
cin>>phil;
if(status[phil]==1)
cout<<"\nAlready eating ;)";
else
{
block1=chopstik[phil].wait();
block2=chopstik[(phil+1)%5].wait();
status[phil]=1;
if(block1==1 || block2==1)
{
if(block1==0)
{
chopstik[phil].signal();
}
else if(block2==0)
{
chopstik[(phil+1)%5].signal();
}
status[phil]=0;
}
}
break;
case 2:
cout<<"\nEnter the philosopher who wants to think:";
cin>>phil;
if(status[phil]==0)
cout<<"\nAlready thinking ;)";
else
{
chopstik[phil].signal();
chopstik[(phil+1)%5].signal();
status[phil]=0;
}
break;
case 3:
for(i=0;i<5;i++)
{
cout<<"\nPhilosopher "<<i+1<<":";
if(status[i+1]==1)
{
cout<<"eating";
}
else
{
cout<<"thinking";
}
}
break;
case 4:
for(i=1;i<=5;i++)
{
if(chopstik[i].s==1 && chopstik[((i+1)%5)].s==1)
{
cout<<"\nPhilosopher "<<i<<" is allowd to eat";
}
}
break;
case 5:
exit(0);
}
}while(ch<=5);
getch();
}
No comments:
Post a Comment