我已经完成了dining philosophers解决方案。由于在某些时候,典型的监视器实现会导致饥饿。在here
中,我已经完成了“礼貌”版本的Dining-philosopher's问题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;
}
}
那么如果两个相邻的哲学家同时饿着怎么办呢?由于测试(i)正在检查其左右哲学家是否感到饥饿。如果它发现它的相邻的一个也饿了。这有点像僵局吗?我的意思是他们两个都不能吃饭,因为他们相邻的哲学家都饿了吗?
答案 0 :(得分:0)
你是对的。如果两个相邻的哲学家在彼此的眼中感到饥饿,就会发生僵局。 leftHungry[0] == TRUE && rightHungry[1] == TRUE
。
但,此状态永远不会发生,因为leftHungry[x]
或rightHungry[x]
设置为TRUE
的唯一时间是x
调用{{ 1}},始终以putDown()
调用x
开头,将pickUp()
和leftHungry[x]
设置为rightHungry[x]
。
例如: FALSE
有philosopher0
,状态为leftHungry[0] == TRUE
,HUNGRY
调用philosopher1
,其状态为那么pickUp()
也是。即使HUNGRY
必须等待,(因为philosopher1
是philosopher2
),EATING
设置philosopher0
,也阻止任何相邻的哲学家同时思考彼此都饿了。