Introduction
The Dining Philosopher's Problem is one of the classic problems we study when we study the operating system. It helps us understand the problems we might face in synchronization and concurrency. This problem also helps us to identify multiple solutions for the same. In this article, we are going to discuss the solution to this problem using Monitors however this problem can also be solved using Semaphores, the link to that article can be found here.
Also Read, FCFS Scheduling Algorithm, Multiprogramming vs Multitasking
Problem Statement
"Five philosophers sit around a circular table. Each philosopher spends his life alternatively thinking and eating. In the center of the table is a large plate of spaghetti. A philosopher needs two forks to eat a helping of spaghetti. Unfortunately, as philosophy is not as well paid as computing, the philosophers can only afford five forks. One fork is placed between each pair of philosophers, and they agree that each will only use the fork to his immediate right and left."
So, the problem can be seen as :
N philosophers seated around a circular table
- There is one fork between each philosopher.
- To eat, a philosopher must pick up their two nearest forks.
- A philosopher must pick up one fork at a time, not both at once.
Possibility of Deadlock
If philosophers take one fork at a time, taking a fork from the left and then one from the right, there is a danger of deadlock.
This possibility of deadlock means that any solution to the problem must include some provision for preventing or otherwise dealing with deadlocks.
Possibility of Starvation
If philosophers take two forks at a time, there is a possibility of starvation. Philosophers P2 & P5 and P1 & P3 can alternate in a way that starves out philosopher P4.
This possibility of starvation means that any solution to the problem must include some provision for preventing starvation.
We require an algorithm to distribute these restricted resources (forks) across numerous processes (philosophers) in such a way that the solution is free from deadlock and starvation.
Some algorithms exist to solve the Dining – Philosopher Problem, although they may have a deadlock situation.
Furthermore, a deadlock-free solution does not always imply a starvation-free solution.
Due to programming flaws, semaphores can cause deadlock.
Monitors alone will not be sufficient to address this problem; we will need monitors with condition variables.