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.
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.
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.
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.