implement Philosophers;
include "sys.m";
sys: Sys;
include "draw.m";
include "rand.m";
rand: Rand;
Philosophers: module {
init: fn(nil: ref Draw->Context, argv: list of string);
};
forks: array of chan of int;
NPHILOSOPERS: con 5;
init(nil: ref Draw->Context, nil: list of string)
{
sys = load Sys Sys->PATH;
rand = load Rand Rand->PATH;
forks = array[NPHILOSOPERS] of {* => chan of int};
for (i := 0; i < len forks; i++)
spawn fork(i, forks[i]);
for (i = 0; i < len forks; i++)
spawn philosopher(i, i, (i + 1) % len forks);
<-chan of int;
}
fork(n: int, c: chan of int)
{
for (;;) {
p := <-c;
c <-= p;
}
}
philosopher(n, f1, f2: int)
{
for (;;) {
if (rand->rand(2) == 0)
(f1, f2) = (f2, f1);
forks[f1] <-= n;
sys->print("philosoper %d picked up fork %d\n", n, f1);
forks[f2] <-= n;
sys->print("philosoper %d picked up fork %d\n", n, f2);
<-forks[f1];
<-forks[f2];
}
}
|