Skip to content
We areTOP 1%

What is the dining philosophers problem, and how can deadlock be avoided in it?

HardConceptProcess Synchronization
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews

Answer

Five philosophers sit at a round table with one fork between each pair, five forks in total. To eat, a philosopher needs both the left and the right fork. The problem models processes that need several shared resources at once.

  • The naive rule, "pick up the left fork, then the right", can deadlock: if all five pick up their left fork together, each waits forever for the right one, which is a circular wait.
  • Resource ordering fixes it: number the forks 0–4 and make every philosopher pick up the lower-numbered fork first, so a cycle can never form.
  • Other fixes: allow at most four philosophers at the table (a counting semaphore starting at 4), or let a philosopher take both forks only when both are free, inside a monitor.
  • A good solution must also avoid starvation, where one philosopher never eats.

Example: philosopher i uses forks i and (i + 1) mod 5. P0 to P3 pick up fork i first, but P4 uses forks 4 and 0, so it picks up fork 0 first. If everyone starts together, P0 and P4 compete for fork 0, and the loser waits holding nothing. The waits therefore cannot close into a cycle, so at least one philosopher always gets both forks, eats and releases them.

More in Process Synchronization

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account