The famous Dining Philosophers’ Problem and Solution

Champika Mendis
2 min readMay 4, 2019

--

What is the Dining Philosopher’s problem?

The dining philosophers problem states that there are 5 philosophers sharing a circular table and they eat and think alternatively. There is a bowl of rice for each of the philosophers and 5 chopsticks. A philosopher needs both their right and left chopstick to eat. A hungry philosopher may only eat if there are both chopsticks available.Otherwise a philosopher puts down their chopstick and begin thinking again.

The dining philosopher is a classic synchronization problem as it demonstrates a large class of concurrency control problems.

The Solution?

From the problem statement, it is clear that a philosopher can think for an indefinite amount of time. But when a philosopher starts eating, he has to stop at some point of time. The philosopher is in an endless cycle of thinking and eating.

for (int i=0;i<number; i++){

philosophers[i]=new Philosopher(i+1);

forks[i]=new Fork(i+1);

}

When a philosopher wants to eat the rice, he will wait for the chopstick at his left and picks up that chopstick. Then he waits for the right chopstick to be available, and then picks it too. After eating, he puts both the chopsticks down.

But if all five philosophers are hungry simultaneously, and each of them pickup one chopstick, then a deadlock situation occurs because they will be waiting for another chopstick forever. The possible solutions for this are:

· A philosopher must be allowed to pick up the chopsticks only if both the left and right chopsticks are available.

· Allow only four philosophers to sit at the table. That way, if all the four philosophers pick up four chopsticks, there will be one chopstick left on the table. So, one philosopher can start eating and eventually, two chopsticks will be available. In this way, deadlocks can be avoided.

System.out.println(“The philosopher : “+philosopherId+”is now picking up the fork: “+left.forkId);

leftpick=left.pick(philosopherId);

if (!leftpick){

return;

}

System.out.println(“The philosopher : “+philosopherId+”is now picking up the fork: “+right.forkId);

rightpick=right.pick(philosopherId);

if (!rightpick){

left.free();

return;

}

--

--

Champika Mendis
Champika Mendis

Written by Champika Mendis

Software Engineering Undergraduate in University of Kelaniya

No responses yet