Operating Systems

Deadlock

Five philosophers sit around a table, with one fork between each pair. Eating requires both neighboring forks. If everyone picks up the left fork at once, nobody can acquire the right one and they wait indefinitely.

A dining-philosophers simulation showing how deadlock arises

1. Choose the fork acquisition rule

2. Run the scenario

Thinking Hungry (waiting for a fork) Eating Deadlock Dashed arrows: requested forks

Make all five hungry lets each philosopher try to take their first fork. Change the rule and repeat to compare the outcomes.

Deadlock requires all four conditions

Mutual exclusion: only one philosopher can use each fork. Hold and wait: a philosopher holds one fork while waiting for another. No preemption: a held fork cannot be forcibly taken away. Circular wait: P0 waits for P1, P1 for P2, and so on, until P4 waits for P0.

Breaking any one of these conditions prevents deadlock.

Break the circular wait

A common approach numbers resources and requires every thread to acquire them in increasing order. For P0–P3 the left fork has the smaller number; for P4 it is right fork 0. Making only P4 start on the right prevents a cycle. Acquiring multiple mutexes in one consistent order uses the same principle.