What is a race condition, and what must a critical-section solution guarantee?
EasyConceptProcess Synchronization
Answer
A race condition occurs when two or more threads access shared data at the same time and the result depends on the exact order in which their instructions run. The part of a program that accesses shared data is its critical section. Any correct solution to the critical-section problem must guarantee three properties:
- Mutual exclusion: at most one process is inside its critical section at a time.
- Progress: if no process is inside, one of those that want to enter must be let in without indefinite delay, and processes not trying to enter cannot block the decision.
- Bounded waiting: once a process asks to enter, there is a limit on how many times others may enter first, so it cannot starve.
Example: count++ is really three steps: load, add 1, store. With count = 5 and two threads:
| Step | Thread A | Thread B | count in memory |
|---|---|---|---|
| 1 | loads 5 | 5 | |
| 2 | loads 5 | 5 | |
| 3 | stores 6 | 6 | |
| 4 | stores 6 | 6 |
Two increments ran, but the result is 6 instead of 7. Wrapping count++ in a lock turns it into a protected critical section and fixes the bug.