我已经完成了哲学家就餐的解决方案。因为在某个时间点,典型的监视器实现会导致饥饿。我已经完成了这里给出的餐饮哲学家问题的“礼貌”版本
monitor diningPhilosophers {
int[] state = new int[5];
boolean[] leftHungry = new boolean[5];
boolean[] rightHungry = new boolean[5];
static final int THINKING = 0;
static final int HUNGRY = 1;
static final int EATING = 2;
condition[] self = new condition[5];
public diningPhilosophers {
for (int i=0;i<5;i++) {
state[i] = THINKING;
leftHungry[i] = false;
rightHungry[i] = false;
}
}
public entry pickUp(int i) {
state[i] = HUNGRY;
test(i);
if (state[i] != EATING)
self[i].wait;
rightHungry(left(i)) = false;
leftHungry(right(i)) = false;
}
ublic entry putDown(int i) {
state[i] = THINKING;
test(left(i));
if (state[left(i)] == HUNGRY)
leftHungry[i] = true;
test(right(i));
if (state[right(i)] == HUNGRY)
rightHungry[i] = true;
}
private test(int i) {
if (state[right(i] != EATING) &&
(state[i] == HUNGRY) &&
(state[left(i)] != EATING) &&
!leftHungry(i) && !rightHungry(i) ) {
state[i] = EATING;
self[i].signal;
}
}
private int left(int i) {
return (i+1)%5;
}
private int right(int i) {
return (i+4)%5;
}
}
那么如果两个相邻的哲学家同时饿了怎么办。因为 test(i) 正在检查它的左右哲学家是否饿了。如果它发现它的相邻的也饿了。这是一种僵局吧?我的意思是他们两个都不能吃,因为他们相邻的哲学家都饿了,对吧?