Solution of Dining Philosophers Problem using Semaphores


Use an array of semaphores chopstick[0..4] all initialized to 1.


repeat

        wait(chopstick[i]);
        wait(chopstick[(i+1) mod 5]);
                . . .
                eat
                . . .
        signal(chopstick[i]);
        signal(chopstick[(i+1) mod 5]);
                . . .
                think
                . . .

until false;


Can suffer from deadlock (e.g. all philosophers decide to eat at the same time and all pick up their left chopstick first) and/or starvation. Some ways to avoid deadlock are:

  1. Don't allow all philosophers to sit and eat/think at once.
  2. Pick up both chopsticks in a critical section
  3. Alternate choice of first chopstick