OS, networking and concurrency · Question 30 of 50
What is a deadlock, and how do you prevent one?
What they're checking
Reasoning about concurrency.
The answer
Two or more tasks each hold something the other needs, and all wait forever: A holds lock 1 and waits for lock 2, while B holds lock 2 and waits for lock 1. It needs four conditions at once: mutual exclusion, hold and wait, no pre-emption, and a circular wait.
Break any one of them. The usual fix is a fixed lock order (always lock the lower account id first), plus timeouts. Databases detect deadlocks and abort one of the transactions, so your code should catch that error and retry.
The picture
A ── holds ──▶ [lock 1] ▲ │ wanted by B wanted ▼ by A [lock 2] ◀── holds ── B circular wait: stuck forever fix: everyone takes lock 1 before lock 2
The follow-up they'll ask
Deadlock, livelock, starvation?
Show the answer
Deadlock: everyone is stuck waiting. Livelock: everyone is busy reacting to each other and nothing progresses. Starvation: one task never gets its turn.
Your progress stays on this device.