Dining Philosophers Deadlock
Problem
Five philosophers sit at a round table with one fork between each adjacent pair (five forks total). A philosopher needs both the fork on their left and the fork on their right to eat, then puts both down and thinks. Model each fork as a threading.Lock and each philosopher as a thread that eats meals times.
Implement a Table class with:
pick_up(i): philosopheriacquires both forks needed to eat.put_down(i): philosopherireleases them.eat(i): a context manager that wraps the two.
Guarantees: the system never deadlocks (every philosopher who wants to eat eventually eats, for any number of meals), no two adjacent philosophers ever eat at the same time (they share a fork), and no philosopher busy-waits.
Also provide a NaiveTable that picks up the left fork then the right fork with no further discipline, and demonstrate in the tests that it does reach a state where every philosopher holds one fork and none can proceed.
n >= 2philosophers,nforks.- You may use
Lock,Semaphore, andCondition; explain which deadlock condition your choice breaks.
Examples
- 5 philosophers, 200 meals each with the ordered-fork
Table→ all 1,000 meals complete in well under a second, and a monitor that records who is eating never sees philosophersiandi+1 mod 5eating together. NaiveTablewith all 5 philosophers forced to hold their left fork at the same instant → every attempt to take the right fork fails, because each right fork is some neighbor's held left fork: the circular wait.- 2 philosophers, 2 forks: both need both forks, so they simply take turns; the ordered
Tablehandles the degenerate ring.
Hints
- Deadlock needs four things at once: mutual exclusion, hold-and-wait, no preemption, and circular wait. You cannot remove the first three for forks; which one can you break?
- If every philosopher always picks up the lower-numbered fork first, can a cycle of "holding one, waiting for the next" ever close?
- A different fix: allow at most
n - 1philosophers to try to eat at once. Why does that guarantee someone always has both forks?
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.