The Dining Philosophers - Problem
Five silent philosophers sit at a round table with bowls of spaghetti. Forks are placed between each pair of adjacent philosophers.
Rules:
- Each philosopher must alternately think and eat
- A philosopher can only eat when they have both left and right forks
- Each fork can be held by only one philosopher at a time
- After eating, philosophers must put down both forks
- No philosopher should starve (deadlock prevention required)
Implementation:
Implement the function void wantsToEat(philosopher, pickLeftFork, pickRightFork, eat, putLeftFork, putRightFork) where:
philosopheris the ID (0-4) of the philosopher who wants to eatpickLeftForkandpickRightForkare functions to pick up forkseatis the function to let the philosopher eatputLeftForkandputRightForkare functions to put down forks
Five threads will simultaneously call this function. Design a deadlock-free solution that prevents starvation.
Input & Output
Example 1 — Basic Philosopher Eating
$
Input:
philosopher = 0, actions = [pickLeftFork, pickRightFork, eat, putLeftFork, putRightFork]
›
Output:
Philosopher 0 successfully eats
💡 Note:
Philosopher 0 acquires fork 0 (left) and fork 1 (right), eats, then releases both forks in proper order.
Example 2 — Multiple Philosophers
$
Input:
philosophers = [0, 1, 2] wanting to eat simultaneously
›
Output:
All philosophers eventually eat without deadlock
💡 Note:
Using asymmetric approach: P0 (even) picks right first, P1 (odd) picks left first, P2 (even) picks right first. This prevents circular waiting.
Example 3 — All Philosophers Competing
$
Input:
All 5 philosophers (0, 1, 2, 3, 4) want to eat at same time
›
Output:
System remains deadlock-free, all philosophers eventually eat
💡 Note:
Semaphore approach allows max 4 philosophers to compete, guaranteeing at least one can acquire both forks and complete the eating cycle.
Constraints
- 5 philosophers numbered 0 to 4
- 5 forks placed between adjacent philosophers
- Multiple threads call wantsToEat() simultaneously
- Must prevent deadlock and starvation
- Each philosopher alternates between thinking and eating
Visualization
Tap to expand
Understanding the Visualization
1
Setup
5 philosophers sit around circular table with 5 forks between them
2
Challenge
Each needs both adjacent forks to eat, but naive approach causes deadlock
3
Solution
Break symmetry with asymmetric fork ordering to prevent circular wait
Key Takeaway
🎯 Key Insight: Break circular symmetry - even philosophers pick right first, odd pick left first
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code