Dining Philosophers Problem
Five philosophers, five forks, and one rule that freezes the table. The classic demonstration that a correct-looking lock order can still deadlock.
Five Philosophers, Five Forks
The dining philosophers problem is a classic operating system synchronization exercise, posed by Edsger Dijkstra, who also set the sleeping barber problem. Five philosophers sit around a circular table. Between each adjacent pair lies a single fork (sometimes called a chopstick), giving five forks for five philosophers.
Each philosopher alternates between thinking and eating. To eat, a philosopher needs both the fork on their left and the fork on their right. A fork can be held by only one philosopher at a time, and a philosopher may not take a fork that a neighbour is already holding.
The problem is to design a protocol for picking up and putting down forks such that no philosopher starves and the table never locks up. It models any situation where processes must acquire multiple shared resources at once — which is why it is the standard illustration of deadlock and its prevention.
- Philosophers stand for processes; forks stand for locks or other shared resources
- Neighbours share a fork, so only neighbours ever compete
- At most two of the five can eat at the same time, since eating takes two of the five forks
- It models processes competing for multiple resources, not dining
Why Left Fork First Deadlocks
- All five become hungry at the same moment.
- Each picks up its left fork: all five succeed.
- All five forks are now held; none is free.
- Each waits on the right fork, held by a neighbour.
- The wait-for graph is a closed cycle of length 5.
- No philosopher can proceed, and none will release.
Check it against the four Coffman conditions: mutual exclusion — a fork is held by one philosopher; hold and wait — each holds one and waits for another; no preemption — nobody can snatch a fork; circular wait — P0 waits on P1 waits on P2 … waits on P0.
All four hold simultaneously, which is exactly the condition for deadlock. Nothing is buggy in any single philosopher's code. The failure lives in the symmetry of the rule, not in any one process.
- Every philosopher holds exactly one fork
- Every philosopher waits on exactly one fork
- The cycle has no entry point for progress
Four Ways to Prevent the Deadlock
- Asymmetry: philosopher 4 takes right then left.
- Limit: semaphore seats = 4 guards the table.
- Atomic: test both neighbours before taking either.
- Hierarchy: always lock the lower-numbered fork first.
Solving the dining philosophers problem using semaphores comes down to one of four rules. Each removes a different Coffman condition.
Asymmetry — make the last philosopher pick up the right fork first. Four reach left, one reaches right, so the cycle cannot close. This is the smallest change that works and costs nothing at runtime.
Limit the diners — admit at most four philosophers to the table using a counting semaphore initialised to 4. With five forks and four diners, at least one diner is guaranteed both forks, so the wait can never close all the way round the table. This breaks circular wait.
All or nothing — pick up both forks in a single atomic operation, or neither. This is what the monitor solution does, and it is the cleanest to reason about.
Resource hierarchy — number the forks and always acquire the lower number first. This is asymmetry generalised, and it is the standard rule in real lock hierarchies.
- Asymmetry breaks circular wait
- Seat limit breaks circular wait
- Atomic pickup breaks hold and wait
- Fork ordering breaks circular wait
Code in Python, C++ and Java
import threading
N = 5
forks = [threading.Lock() for _ in range(N)]
meals = [0] * N
def dine(i, rounds):
"""Philosopher i eats `rounds` times, then stops."""
left, right = i, (i + 1) % N
# The asymmetry: the last philosopher takes its right fork first.
# Four reach left-first and one reaches right-first, so the
# wait-for graph can never close into a cycle.
first, second = (right, left) if i == N - 1 else (left, right)
for _ in range(rounds):
with forks[first]:
with forks[second]:
meals[i] += 1
def main():
# 1000 meals each, so the five threads really do fight over the forks.
threads = [threading.Thread(target=dine, args=(i, 1000)) for i in range(N)]
for t in threads:
t.start()
for t in threads:
t.join()
for i in range(N):
first, second = (0, N - 1) if i == N - 1 else (i, i + 1)
print(f"P{i} takes fork {first} then fork {second}: ate {meals[i]} times")
print("all 5 finished: no deadlock")
if __name__ == "__main__":
main()
#include <array>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
constexpr int N = 5;
std::array<std::mutex, N> forks;
std::array<int, N> meals {
};
void dine(int i, int rounds) {
int left = i, right = (i + 1) % N;
// The asymmetry: the last philosopher takes its right fork first,
// so the wait-for graph can never close into a cycle.
int first = (i == N - 1) ? right : left;
int second = (i == N - 1) ? left : right;
for (int r = 0; r < rounds; r++) {
std::lock_guard<std::mutex> a(forks[first]);
std::lock_guard<std::mutex> b(forks[second]);
meals[i]++;
}
}
int main() {
std::vector<std::thread> threads;
// 1000 meals each, so the five threads really do fight over the forks.
for (int i = 0; i < N; i++) threads.emplace_back(dine, i, 1000);
for (auto& t : threads) t.join();
for (int i = 0; i < N; i++) {
int first = (i == N - 1) ? 0 : i, second = (i == N - 1) ? N - 1 : i + 1;
std::cout << "P" << i << " takes fork " << first << " then fork " << second
<< ": ate " << meals[i] << " times\n";
}
std::cout << "all 5 finished: no deadlock\n";
}import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Main {
static final int N = 5;
static final Lock[] forks = new Lock[N];
static final int[] meals = new int[N];
static void dine(int i, int rounds) {
int left = i, right = (i + 1) % N;
// The asymmetry: the last philosopher takes its right fork first,
// so the wait-for graph can never close into a cycle.
int first = (i == N - 1) ? right : left;
int second = (i == N - 1) ? left : right;
for (int r = 0; r < rounds; r++) {
forks[first].lock();
try {
forks[second].lock();
try {
meals[i]++;
}
finally {
forks[second].unlock();
}
}
finally {
forks[first].unlock();
}
}
}
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < N; i++) forks[i] = new ReentrantLock();
// 1000 meals each, so the five threads really do fight over the forks.
Thread[] threads = new Thread[N];
for (int i = 0; i < N; i++) {
final int id = i;
threads[i] = new Thread(() -> dine(id, 1000));
threads[i].start();
}
for (Thread t : threads) t.join();
for (int i = 0; i < N; i++) {
int first = (i == N - 1) ? 0 : i, second = (i == N - 1) ? N - 1 : i + 1;
System.out.println("P" + i + " takes fork " + first + " then fork " + second
+ ": ate " + meals[i] + " times");
}
System.out.println("all 5 finished: no deadlock");
}
}Step through it
Running on 5 philosophers, 5 forks, all hungry at once
The Monitor Solution and Starvation
The monitor version gives each philosopher a state — thinking, hungry or eating — and one condition variable each.
A hungry philosopher calls test(), which allows eating only if it is hungry and neither neighbour is eating. Because the monitor guarantees mutual exclusion, that check and the transition to eating happen atomically — the philosopher never holds one fork while waiting for the other.
When a philosopher finishes, it calls test() on both neighbours, waking anyone who can now proceed. That is what turns a deadlock-free solution into a responsive one.
Deadlock is impossible here, but plain test() does not guarantee starvation freedom: a philosopher with two constantly-eating neighbours may never be signalled. Bounded waiting needs an extra rule, such as refusing a philosopher who has eaten more recently than a waiting neighbour.
- State per philosopher, condition variable per philosopher
- test() checks self and both neighbours atomically
- Deadlock free by construction
- Starvation still needs an explicit fairness rule
What the Problem Is Actually Teaching
The lasting lesson is that correctness of each process does not imply correctness of the system. Every philosopher's algorithm is locally reasonable; the dining philosophers deadlock is a property of how five copies interact.
The second lesson is that symmetry is dangerous in concurrent systems. The cheapest fix — making one philosopher behave differently — is the one that breaks the cycle, and generalises to the lock-ordering rule used in every large codebase: acquire locks in a globally agreed order and cycles become impossible.
Any time code holds one lock while asking for a second, this problem is present. The forks are incidental.
- Local correctness does not compose into global correctness
- Global lock ordering is the industrial form of the fix
- Holding one lock while requesting another is the danger sign