We develop this program in the following steps. First, the library is included as sim.h. The declarations of the
global variables and constants follow after that. The time unit in this simulation is an hour, so a philosopher has
a mean eating time of two hours and a mean thinking time of five hours. The duration of the simulation is a
year. After that, we define the various events.
a year
const int number = 5; philosophers
const int eatingtime = 2; 2 hours
const int thinkingtime = 5; 5 hours
simulation* sim;
generator* g;
resource* chopstick[number];
histogram* thinking;
constructor, taking identity
virtual int operator()(); function operator
private :
int id; identity of the philosopher
};
class think : public event
{
public :
think(int i); constructor, taking identity
virtual int operator()(); function operator
private :
int id; identity of the philosopher
};
class await : public event
{
public :
await(int i); constructor, taking identity
virtual int operator()(); function operator
private :
int id; identity of the philosopher
};
The logic of the eat event is that the philosopher eats for a random time, exponentially distributed with a mean
eating time. So, we first determine the actual eating time and schedule a think event to be activated after this
eating time. The eat event can be terminated.
set identity
}
int eat::operator()()
{
double t = g -> exponential(eatingtime); eating time
think* th = new think(id); create a thinking event
sim -> schedule(th,t); schedule thinking
sim -> terminate(this); terminate this eat event
return OK;
}
set identity
}
int think::operator()()
{
chopstick[id] -> release(); release left chopstick
chopstick[(id+1) % number] -> release(); release right
double t = g -> exponential(thinkingtime); thinking time
thinking -> sample(id,t/duration*100); add a sample (%)
await* aw = new await(id); create await event
sim -> schedule(aw,t); schedule waiting
sim -> terminate(this); terminate thinking
return OK;
}
set identity
}
int await::operator()()
{
if ( (chopstick[id] -> available()) && available ?
(chopstick[(id+1) % number] -> available()) )
{
chopstick[id] -> acquire(); acquire left
chopstick[(id+1) % number] -> acquire(); acquire right
eat* e = new eat(id);
sim -> passivate(this); extract from conditional list
sim -> schedule(e,0); schedule eat event immediately
sim -> terminate(this); terminate await event
}
else if (!conditional()) not on conditional list
sim -> hold(this); add to conditional list
return OK;
}
tk is an instance variable of session
{
sim = new simulation();
g = new generator(80,20,19); gets three seeds
thinking = new histogram(".h","-columns 5 -title thinkingtime");
tk -> pack(thinking); add to display;
tk -> update(); update display;
for (int i=0;i
await* aw = new await(i); schedule each
sim -> schedule(aw,0); philosopher waiting
}
sim -> run(duration); run for duration
cout << (*thinking) << endl; print resulting histogram
delete thinking;
delete sim;
return 0; successful termination
}