1
4.7kviews
Explain The Dining-Philosophers Problem Solution using monitor.
1 Answer
1
471views

Dining-Philosophers Solution Using Monitors

• We now illustrate monitor concepts by presenting a deadlock-free solution to the dining- philosophers problem.

• This solution imposes the restriction that a philosopher may pick up his chopsticks only if both of them are available.

• To code this solution, we need to distinguish among three states in which we may find a philosopher. For this purpose, we introduce the following data structure:

enum { thinking, hungry, eating } state [5];

• Philosopher i can set the variable state [i] = eating only if his two neighbors are not eating: (state [(i+4) % 5] != eating) and (state [(i+1)% 5] != eating).

• We also need to declare condition self [5]; where philosopher i can delay himself when he is hungry but is unable to obtain the chopsticks he needs.

A monitor solution to the dining-philosopher problem

monitor dp {
enum { THINKING, HUNGRY, EATING} state [5];
condition self [5];
void pickup (int i) {
state [i] = HUNGRY;
test (i) ;
if (state [i]!= EATING)
self [i].wait() ;
}
void putdown(int i) {
state [i] = THINKING;
test ((i + 4) % 5);
test ((i + 1) % 5);

             ir
}


void test (int i) {
      if ((state [(i + 4) % 5] != EATING) &&
            (state [i] == HUNGRY) &&
           (state [(i + 1) % 5]!= EATING)) {
                  state [i] = EATING;
                  self [i].signal() ;

            }
initialization-code () {
      for (int i = 0; i < 5; i++) 
      state [i] = THINKING; 
     }

}

Please log in to add an answer.