Homework: Dining Philosophers
Pseudocode for Dining Philosophers
A solution to the dining philosophers problem that
uses a (pseudo)monitor and condition variables:
pseudomonitor DiningPhilosophers
{
enum State {THINKING, HUNGRY, EATING};
State[] states = new State[5];
Condition[] self = new Condition[5];
public DiningPhilosophers {
for(int i = 0; i < 5; i++) {
state[i] = State.thinking;
}
}
public void takeForks(int i) {
state[i] = State.HUNGRY;
test(i);
if(state[i] != State.EATING)
self[i].wait;
}
public void returnForks(int i) {
state[i] = State.THINKING;
// test left and right neighbors
test((i + 4) % 5);
test((i + 1) % 5);
}
private void test(int i) {
if( (state[(i + 4) % 5] != State.EATING) &&
(state[i] == State.HUNGRY) &&
(state[(i + 1) % 5] != State.EATING) ) {
state[i] = State.EATING;
self[i].signal;
}
}
}
John Casey
Last modified: Thu Feb 19 09:21:17 EST 2009