Problem solving · should-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix

Dining Philosophers Deadlock

mediumconcurrency

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): philosopher i acquires both forks needed to eat.
  • put_down(i): philosopher i releases 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 >= 2 philosophers, n forks.
  • You may use Lock, Semaphore, and Condition; 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 philosophers i and i+1 mod 5 eating together.
  • NaiveTable with 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 Table handles the degenerate ring.

Hints

  1. 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?
  2. If every philosopher always picks up the lower-numbered fork first, can a cycle of "holding one, waiting for the next" ever close?
  3. A different fix: allow at most n - 1 philosophers to try to eat at once. Why does that guarantee someone always has both forks?

Last reviewed 8 September 2026