Dining Philosophers Problem in Operating System (OS)

Dining Philosophers in Operating System

Dining Philosophers essentially is a process synchronization example and ​helps understanding how we can simultaneously utilise common resources of multiple processes together.

Entities –

  • Noodles/Rice
  • Chopstics
  • Philosophers

Imagine five philosophers sitting around circular table and have a bowl of rice or noodles in the middle and there are five chopsticks on the table.

At any given instance, a philosophers will do –

  • Thinking
  • Eating
  • Whenever the philosophers wants to eat. He obviously will use two chopstick together.
    • So to eat both chopsticks on his right and left must be free.
  • Whenever he is thinking
    • He must put down both the chopsticks back at the table.
Dining Philosophers Problem OS Operating System

Rules and Solution

If a philosopher decides to eat he first will wait for the chopstick on his left to be free. If its already free then he will pick that up. Then only he will wait for the chopstick on his right and once free pick that up too and do the eating.

A deadlock condition may arise here, consider if all the philosopher get hungry simultaneously together and they pick up one chopstick. In this case they will wait indefinitely for their 2nd chopstick and deadlock will be there forever.

        mod is used because if i=5, next 
        chopstick is 1 (dining table is circular)
    wait(stick[(i+1) % 5]);  
    /* eat */
    signal(stick[(i+1) % 5]); 
    /* think */

Some of the ways to avoid deadlock are as follows:

  • There should be at most four philosophers on the table. In this way one chopstick will be extra if all decide to eat together. This one chopstick then can be used by one of our philosopher and he will finish his eating and then two chopsticks are available then 1 more can eat and so on…
  • Solving with even and odd technique, even philosopher must pick his right and off must pick his left.
  • Only and only if both chopsticks are available at the same time for a philosopher then only he should pick them up,