Dining Philosophers Problem
Last Updated :
18 Nov, 2024
The Dining Philosopher Problem is a classic synchronization and concurrency problem that deals with resource sharing, deadlock, and starvation in systems where multiple processes require limited resources. In this article, we will discuss the Dining Philosopher Problem in detail along with proper implementation.
Problem Statement
The Dining Philosopher Problem involves 'n' philosophers sitting around a circular table. Each philosopher alternates between two states: thinking and eating. To eat, a philosopher needs two chopsticks, one on their left and one on their right. However, the number of chopsticks is equal to the number of philosophers, and each chopstick is shared between two neighboring philosophers.
The standard problem considers the value of 'n' as 5 i.e. we deal with 5 Philosophers sitting around a circular table.
Constraints and Conditions for the Problem
- Every Philosopher needs two forks to eat.
- Every Philosopher may pick up the forks on the left or right but only one fork at once.
- Philosophers only eat when they have two forks. We have to design such a protocol i.e. pre and post protocol which ensures that a philosopher only eats if he or she has two forks.
- Each fork is either clean or dirty.

Solution
The correctness properties it needs to satisfy are:
- Mutual Exclusion Principle: No two Philosophers can have the two forks simultaneously.
- Free from Deadlock: Each philosopher can get the chance to eat in a certain finite time.
- Free from Starvation: When few Philosophers are waiting then one gets a chance to eat in a while.
- No strict Alternation
- Proper utilization of time
Algorithm
loop forever
p1: think
p2: preprotocol
p3: eat
p4: postprotocol
First Attempt
We assume that each philosopher is initialized with its index I and that addition is implicitly modulo 5. Each fork is modeled as a semaphore where wait corresponds to taking a fork and signal corresponds to putting down a fork.
Algorithm
semaphore array[0..4] fork â [1, 1, 1, 1, 1]
loop forever
p1 : think
p2 : wait(fork[i])
p3 : wait(fork[i + 1])
p4 : eat
p5 : signal(fork[i])
p6 : signal(fork[i + 1])
Problem with this solution:
This solution may lead to a deadlock under an interleaving that has all the philosophers pick up their left forks before any of them tries to pick up a right fork. In this case, all the Philosophers are waiting for the right fork but no one will execute a single instruction.
Second Attempt
One way to tackle the above situation is to limit the number of philosophers entering the room to four. By doing this one of the philosophers will eventually get both the fork and execute all the instruction leading to no deadlock.
Algorithm
semaphore array[0..4] fork â [1, 1, 1, 1, 1]
semaphore room â 4
loop forever
p1 : think
p2 : wait(room)
p3 : wait(fork[i])
p4 : wait(fork[i + 1])
p5 : eat
p6 : signal(fork[i])
p7 : signal(fork[i + 1])
p8 : signal(room)
In this solution, we somehow interfere with the given problem as we allow only four philosophers.
Third Attempt
We use the asymmetric algorithm in the attempt where the first four philosophers execute the original solution but the fifth philosopher waits for the right fork and then for the left fork.
Algorithm
semaphore array [0..4] fork â [1,1,1,1,1]
For the first Four Philosophers
loop forever
p1 : think
p2 : wait(fork[i])
p3 : wait(fork[i + 1])
p4 : eat
p5 : signal(fork[i])
p6: signal(fork[i + 1])
For the Fifth Philosopher
loop forever
p1 : think
p2 : wait(fork[0])
p3 : wait(fork[4])
p4 : eat
p5 : signal(fork[0])
p6 : signal(fork[4])
Note: This solution is also known as Chandy/Misra Solution.
Advantages of this Solution
- Allows a large degree of concurrency
- Free from Starvation
- Free from Deadlock
- More Flexible Solution
- Economical
- Fairness
- Boundedness
The above discussed the solution for the problem using semaphore. Now with monitors, Here, Monitor maintains an array of the fork which counts the number of free forks available to each philosopher. The take Forks operation waits on a condition variable until two forks are available. It decrements the number of forks available to its neighbor before leaving the monitor. After eating, a philosopher calls release Forks which updates the array fork and checks if freeing these forks makes it possible to signal.
Algorithm
monitor ForkMonitor:
integer array[0..4]
fork â [2,2,2,2,2]
condition array[0..4]OKtoEat
operation takeForks(integer i)
if(fork[i]!=2)
waitC(OKtoEat[i])
fork[i+1]<- fork[i+1]-1
fork[i-1] <- fork[i-1]-1
operation releaseForks(integer i)
fork[i+1] <- fork[i+1]+1
fork[i-1] <- fork[i-1]
if(fork[i+1]==2)
signalC(OKtoEat[i+1])
if(fork[i-1]==2)
signalC(OKtoEat[i-1])
For Each Philosopher
loop forever :
p1 : think
p2 : takeForks(i)
p3 : eat
p4 : releaseForks(i)
Here Monitor will ensure all such needs mentioned above.
Implementation of Dining Philosophers Problem
Here is the Program for the same using monitors in C++ as follows.
C++14
// Header file include
#include <bits/stdc++.h>
#include <pthread.h>
#include <unistd.h>
using namespace std;
#define N 10
#define THINKING 2
#define HUNGRY 1
#define EATING 0
#define LEFT (phnum + 4) % N
#define RIGHT (phnum + 1) % N
// Philosopher index
int phil[N];
int times = 200;
class monitor
{
// state of the philosopher
int state[N];
// Philosopher condition variable
pthread_cond_t phcond[N];
// mutex variable for synchronization
pthread_mutex_t condLock;
public:
// Test for the desired condition
// i.e. Left and Right philosopher are not reading
void test(int phnum)
{
if (state[(phnum + 1) % 5] != EATING and state[(phnum + 4) % 5] != EATING and state[phnum] == HUNGRY)
{
state[phnum] = EATING;
pthread_cond_signal(&phcond[phnum]);
}
}
// Take Fork function
void take_fork(int phnum)
{
pthread_mutex_lock(&condLock);
// Indicates it is hungry
state[phnum] = HUNGRY;
// test for condition
test(phnum);
// If unable to eat.. wait for the signal
if (state[phnum] != EATING)
{
pthread_cond_wait(&phcond[phnum], &condLock);
}
cout << "Philosopher " << phnum << " is Eating" << endl;
pthread_mutex_unlock(&condLock);
}
// Put Fork function
void put_fork(int phnum)
{
pthread_mutex_lock(&condLock);
// Indicates that I am thinking
state[phnum] = THINKING;
test(RIGHT);
test(LEFT);
pthread_mutex_unlock(&condLock);
}
// constructor
monitor()
{
for (int i = 0; i < N; i++)
{
state[i] = THINKING;
}
for (int i = 0; i < N; i++)
{
pthread_cond_init(&phcond[i], NULL);
}
pthread_mutex_init(&condLock, NULL);
}
// destructor
~monitor()
{
for (int i = 0; i < N; i++)
{
pthread_cond_destroy(&phcond[i]);
}
pthread_mutex_destroy(&condLock);
}
}
// Global Object of the monitor
phil_object;
void *philosopher(void *arg)
{
int c = 0;
while (c < times)
{
int i = *(int *)arg;
sleep(1);
phil_object.take_fork(i);
sleep(0.5);
phil_object.put_fork(i);
c++;
}
}
int main()
{
// Declaration...
pthread_t thread_id[N];
pthread_attr_t attr;
// Initialization...
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for (int i = 0; i < N; i++)
{
phil[i] = i;
}
// Creating...
for (int i = 0; i < N; i++)
{
pthread_create(&thread_id[i], &attr, philosopher, &phil[i]);
cout << "Philosopher " << i + 1 << " is thinking..." << endl;
}
// Joining....
for (int i = 0; i < N; i++)
{
pthread_join(thread_id[i], NULL);
}
// Destroying
pthread_attr_destroy(&attr);
pthread_exit(NULL);
return 0;
}
Python
# Importing required libraries
import threading
import time
# Constants
N = 10
THINKING = 2
HUNGRY = 1
EATING = 0
times = 200
# Philosopher index
phil = [i for i in range(N)]
class Monitor:
def __init__(self):
# state of the philosopher
self.state = [THINKING] * N
# Philosopher condition variable
self.phcond = [threading.Condition() for _ in range(N)]
# Test for the desired condition
# i.e. Left and Right philosopher are not eating
def test(self, phnum):
with self.phcond[phnum]:
if (self.state[(phnum + 1) % N] != EATING and
self.state[(phnum + N - 1) % N] != EATING and
self.state[phnum] == HUNGRY):
self.state[phnum] = EATING
self.phcond[phnum].notify()
# Take Fork function
def take_fork(self, phnum):
with self.phcond[phnum]:
# Indicates it is hungry
self.state[phnum] = HUNGRY
# test for condition
self.test(phnum)
# If unable to eat.. wait for the signal
if self.state[phnum] != EATING:
self.phcond[phnum].wait()
print(f"Philosopher {phnum} is Eating")
# Put Fork function
def put_fork(self, phnum):
with self.phcond[phnum]:
# Indicates that I am thinking
self.state[phnum] = THINKING
self.test((phnum + 1) % N)
self.test((phnum + N - 1) % N)
# Global Object of the monitor
phil_object = Monitor()
def philosopher(phnum):
c = 0
while c < times:
time.sleep(1)
phil_object.take_fork(phnum)
time.sleep(0.5)
phil_object.put_fork(phnum)
c += 1
def main():
# Creating...
threads = []
for i in range(N):
t = threading.Thread(target=philosopher, args=(phil[i],))
threads.append(t)
t.start()
print(f"Philosopher {i + 1} is thinking...")
# Joining....
for i in range(N):
threads[i].join()
if __name__ == "__main__":
main()
Output
Output for Dining Philosophers problem for the above programConclusion
The Dining Philosopher Problem teaches us how to handle shared resources in a system while avoiding issues like deadlock and starvation. It highlights challenges like deadlock and starvation and teaches how to prevent them using proper synchronization techniques. The problem is a classic example used to study synchronization and resource allocation in concurrent systems.
Similar Reads
Dining Philosopher Problem Using Semaphores
The Dining Philosopher Problem states that K philosophers are seated around a circular table with one chopstick between each pair of philosophers. There is one chopstick between each philosopher. A philosopher may eat if he can pick up the two chopsticks adjacent to him. One chopstick may be picked
11 min read
Dining-Philosophers Solution Using Monitors
Prerequisite: Monitor, Process Synchronization Dining-Philosophers Problem - N philosophers seated around a circular table There is one chopstick between each philosopherA philosopher must pick up its two nearest chopsticks in order to eatA philosopher must pick up first one chopstick, then the se
4 min read
Classical Problems of Synchronization with Semaphore Solution
With the evolution of multi-processors, tasks suffer due to overheads and traffic. To manage the resources efficiently, synchronization is needed. Synchronization ensures perfect execution of processes and controlled access to shared resources. Synchronization in operating systems is often explained
4 min read
Nutanix Interview Experience - Campus Placements
Nutanix Technologies came to our campus BITS Goa for On-Campus Recruitment process. They conducted multiple rounds of screening to finally select 3 Candidates. Online Test: Hackerrank platform We were allotted 1 hr to solve two problems. 1st question: Given n tailors with particular skill values (po
5 min read
Food Ordering System in C
Prerequisite: Modular Approach in Programming Problem Statement: Write C program to implement Food ordering with the following functionalities: Login & SignupSearch by FoodSearch by hotelsCart & Order Confirmation Approach and Functionality: Signup Functionality This is the main function for
15+ min read
Maximum Tip Calculator
Rahul and Ankit are the only two waiters in Royal Restaurant. Today, the restaurant received N orders. The amount of tips may differ when handled by different waiters, if Rahul takes the ith order, he would be tipped Ai rupees and if Ankit takes this order, the tip would be Bi rupees. In order to ma
15+ min read
Maximum candies two friends can eat
Given six integers X, Y, cnt1, cnt2, C1, and C2, where: X and Y represent the maximum calories two friends can consume,cnt1 and cnt2 are the numbers of two types of candies,C1 and C2 are the calories present in each candy of the two types of available candies. The task is to find the maximum number
7 min read
Puzzle | Marriage Party
3 types of people go to a marriage party. Type 1 people : 1 man eats in 4 plates. Type 2 people : 1 man eats in 2 plates. Type 3 people : 4 men eat in 1 plate. You are given that exactly 100 people go to the party and there are exactly 100 plates. So you have to calculate how many people of type 1,
2 min read
CSES Solutions - Restaurant Customers
You are given the arrival and leaving times of N customers in a restaurant as array customers[][], such that customer[i][0] is the arrival time and customer[i][1] is the leaving time. What was the maximum number of customers in the restaurant at any time? You may assume that all arrival and leaving
6 min read
Puzzle | The Pizza Trouble
Rachel and Ross are about to eat pizzas. Apparently, both of them are hungry and have a huge appetite. So Ross brings 5 pizzas while Rachel brings 3 pizzas. Each pizza has six slices in total. They're about to sit together and eat when suddenly Joey turns up. Joey agrees to give them money in return
2 min read