0

我已经完成了哲学家就餐的解决方案。因为在某个时间点,典型的监视器实现会导致饥饿。我已经完成了这里给出的餐饮哲学家问题的“礼貌”版本

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) 正在检查它的左右哲学家是否饿了。如果它发现它的相邻的也饿了。这是一种僵局吧?我的意思是他们两个都不能吃,因为他们相邻的哲学家都饿了,对吧?

4

1 回答 1

0

你是对的。如果两个相邻的哲学家在彼此的眼中饿了,就会发生死锁,即。leftHungry[0] == TRUE && rightHungry[1] == TRUE.

但是,这种状态永远不会发生,因为唯一的时间leftHungry[x]orrightHungry[x]被设置为调用TRUE时,它总是在调用之前,它设置和到。xputDown()xpickUp()leftHungry[x]rightHungry[x]FALSE

例如: philosopher0 hasleftHungry[0] == TRUE和他们的状态是HUNGRY,并且philosopher1调用pickUp()和他们的状态也是 then HUNGRY。即使philosopher1必须等待,(因为philosopher2EATING),philosopher0设置leftHungry[0] == FALSE,防止任何相邻的哲学家同时认为彼此饿了。

于 2013-04-07T02:00:02.363 回答