Skip to content
We areTOP 1%

What is a race condition, and what must a critical-section solution guarantee?

EasyConceptProcess Synchronization
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews

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:

StepThread AThread Bcount in memory
1loads 55
2loads 55
3stores 66
4stores 66

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.

More in Process Synchronization

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account