Skip to content
BENIBIX Learn

Race Condition vs Deadlock

A race condition and a deadlock are both bugs that come from threads sharing data, but they fail in opposite ways. In a race, two threads touch the same data at once with no lock, and the result comes out wrong. In a deadlock, threads hold locks and wait for each other, so nothing runs at all. A race gives wrong answers; a deadlock gives none.

Development⚙️ Compilers & Runtimes

Race Condition

A bug where the result depends on which task gets there first.

A race condition is a bug where the result depends on which of two tasks gets there first. It happens when threads or requests read and change the same data at the same time. Adding 1 to a number is really three steps: read it, add, write it back. If two threads do this at once, one write can wipe out the other. The bug appears only now and then, which makes it hard to find.

Example
Jack's shop has 1 item left. Two buyers click at the same moment, both checks see 1 in stock, and the item is sold twice.
Why it matters
Race bugs pass tests. Then they fail in real use, when many users act at the same moment.
Full entry
Development⚙️ Compilers & Runtimes

Deadlock

Two tasks each wait for the other. So neither can ever go on.

A deadlock is when two tasks each wait for something the other holds. Then none of them can go on. Thread A holds lock 1 and waits for lock 2. Thread B holds lock 2 and waits for lock 1. Neither will ever let go, so the program freezes with no error. The usual fix is to always take locks in the same order everywhere.

Example
Emma's bank app moves money between two accounts. One thread locks Lucy then Jack, the other locks Jack then Lucy. Both wait forever.
Why it matters
A deadlock gives no error message. The app just stops, which makes it one of the hardest bugs to spot.
Full entry

In one line

Race Condition
A bug where the result depends on which task gets there first.
Deadlock
Two tasks each wait for the other. So neither can ever go on.