/    /  OS – Dining Philosophers Problem

Dining Philosophers Problem

 

Dining philosophers’ problem is one of the classical problems of synchronization.

In this problem, there are five philosophers sitting around a circular table with one chopstick in between each of them. If they want to eat they will have to pick the chopsticks adjacent to them first. This problem deals with allocating limited resources to multiple processes. 

 

Solution:

We can take five semaphores, stick[5], signifying the five chopsticks. 

When the philosopher wants to eat he will have to pick the chopstick from his left and right, he will wait for them if they are not available. After eating he will put the chopstick down.

 

The problem arises if all of the philosophers are hungry at once and takes one chopstick each, then there will be a situation of deadlock, as the philosophers will never get the second chopstick.

 

The possible solutions can be:

  1. The chopsticks should be picked only when there are two of them available at the same time.
  2. Only four philosophers are allowed at the table, that way there will be four chopsticks. One philosopher can start eating, and still, there will be two chopsticks left, and the situation of the deadlock can be solved.

 

The program of each philosopher will look something like this:

 

Reference

Dining Philosophers Problem