Plan 9 from Bell Labs’s /usr/web/sources/contrib/rog/sh-examples/demo/deadlock.demo/philosophers.b

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


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: int, f1, f2: int)
{
	for (;;) {
		if (rand->rand(2) == 0)
			(f1, f2) = (f2, f1);
		sys->print("philosopher %d picking up fork %d\n", n, f1);
		forks[f1] <-= n;
		sys->print("philosopher %d picking up fork %d\n", n, f2);
		forks[f2] <-= n;
		sys->print("philosopher %d dropping fork %d\n", n, f1);
		<-forks[f1];
		sys->print("philosopher %d dropping fork %d\n", n, f2);
		<-forks[f2];
	}
}

Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to webmaster@9p.io.