Sunday, February 6, 2011

Dinning Philosopher Problem


OBJECTIVE: Implementation of process synchronization(DINNING PHILOSOPHER PROBLEM)
THEORY: The goal of problem is to create a program that simulate the behavior of 5 philosopher gathered around a table  to think and eat.
Each philosopher has one fork, but needs two forks to eat.Thus the pholoshper  decide to share their forks. When a philosopher wants to eat, he takes the fork on his left,whwn it is available,then the fork on his right,eats,and then puts forks back.
After the philosopher have thought and eaten several times ,it may happen that all philosophers simultaneously decide to eat.they take their left fork,and find the right forkalready taken by their right neighbor.In this case,if nothing has been foreseen the philosopher will stay in that situation(deadlock)indefinitely.the program should avoid that situation.

PROGRAM:

#include<sim/sim.h>
const double duration=52*7*24.0;
const int number =5;
const int eatingtime=2;
const int thinkingtime=5;
simulation*sim;
generator*g;
resource*chopstic[number];
histogram*thinking;
class eat:public event
{
public:
eat(int i);
virtual int operator()();
private:
int id;
};
Class think:public event
{
Public:
think(int i);
virtual int operator()();
private:
int id;
};
Class await:public event
{
public:
await(int i)
virtual int operator()();
private:
int id;
};
eat::eat(int i):event()
{
Id=I;
}
int eat::operator()()
{
double t=g->exponential(eatingtime);
think*th=new think(id);
sim->schedule(th,t);
sim->terminate(this);
return ok;
}
think::think(int i):event()
{
id=I;
}
Int think::operator()()
{
chopstick[id]->release();
chopstick[id+1]%number->release();
double t=g->exponential(thinkingtime);
thinking->sample(id,t/duration*100);
await*aw=new await(id);
sim->schedule(aw,t);
sim->terminate(this);
return ok;
}
await::await(int i):event()
{
id=I;
}
Int await::operator()()
{
If((chopstick[id]->available()&&(chopstick[(id+1)%number]->available()))
{
chopstick[id]->acquire();
chopstick[id+1]%number->acquire();
eat*e=new eat(id);
sim->passivate(this);
sim->schedule(e,o);
sim->terminate(this);
}
else if(!conditional())
sim->hold(this);
return ok;
}
class application:public session
{
public:
application(int argc,char**argv);
int main();
};
application::application(int argc,char**argv):session(argc,argv,”philosophers”)
{}
int application::main()
{
sim=new simulation();
g=new generator(80,20,19);
thinking=new histogram(“.h”,”-columns 5-title thinkingtime”);
tk->pack(thinkingtime);
tk->update();
for(int i=0;i<number,i++)
{
chopstick[i]=new resource(1);
await*aw=new await(i);
sim->schedule(aw,0);
}
sim->run(duration);
cout<<(*thinking)<<endl;
delete thinking;
delete sim;
return 0;
}
main(int,char**argv)
{
session*s=new application(argc,argv);
return s->run();
}


No comments:

Post a Comment