RosettaCodeData/Task/Dining-philosophers/D/dining-philosophers.d

39 lines
984 B
D
Raw Permalink Normal View History

2013-04-10 16:57:12 -07:00
import std.stdio, std.algorithm, std.string, std.parallelism,
2014-01-17 05:32:22 +00:00
core.sync.mutex;
2013-04-10 16:57:12 -07:00
2014-01-17 05:32:22 +00:00
void eat(in size_t i, in string name, Mutex[] forks) {
2013-04-10 16:57:12 -07:00
writeln(name, " is hungry.");
immutable j = (i + 1) % forks.length;
// Take forks i and j. The lower one first to prevent deadlock.
auto fork1 = forks[min(i, j)];
auto fork2 = forks[max(i, j)];
2014-01-17 05:32:22 +00:00
fork1.lock;
scope(exit) fork1.unlock;
2013-04-10 16:57:12 -07:00
2014-01-17 05:32:22 +00:00
fork2.lock;
scope(exit) fork2.unlock;
2013-04-10 16:57:12 -07:00
writeln(name, " is eating.");
writeln(name, " is full.");
}
void think(in string name) {
writeln(name, " is thinking.");
}
void main() {
2014-01-17 05:32:22 +00:00
const philosophers = "Aristotle Kant Spinoza Marx Russell".split;
2013-04-10 16:57:12 -07:00
Mutex[philosophers.length] forks;
foreach (ref fork; forks)
2014-01-17 05:32:22 +00:00
fork = new Mutex;
2013-04-10 16:57:12 -07:00
defaultPoolThreads = forks.length;
2013-10-27 22:24:23 +00:00
foreach (i, philo; taskPool.parallel(philosophers)) {
2014-01-17 05:32:22 +00:00
foreach (immutable _; 0 .. 100) {
2013-04-10 16:57:12 -07:00
eat(i, philo, forks);
2014-01-17 05:32:22 +00:00
philo.think;
2013-04-10 16:57:12 -07:00
}
}
}