What is a race condition, and what is a critical section?
Short answer: A race condition is a bug where the result depends on the timing of two or more concurrent activities that access shared data, at least one of them writing. A critical section is the piece of code that accesses that shared data and must not be executed by more than one task at a time. Protecting critical sections (mutual exclusion) prevents races.
The classic example: count++ is not atomic. It is three steps: load, add, store.
Thread A: load count (5)
Thread B: load count (5)
Thread A: add 1, store 6
Thread B: add 1, store 6 ← one increment lost; expected 7
Ways to protect a critical section
| Technique | When |
|---|---|
| Mutex | threads/tasks; the section may block |
| Spinlock | very short sections, multi-core, cannot sleep (kernel, ISRs with IRQs disabled) |
| Disable interrupts | single-core MCU, task vs ISR, very short sections |
Atomic operations (stdatomic.h, LDREX/STREX, LDADD) |
single variables, counters, flags |
| Avoid sharing | message passing, per-thread data, single owner |
Requirements for a correct critical-section solution: mutual exclusion (only one inside), progress (if nobody is inside, someone waiting can enter), and bounded waiting (nobody waits forever).
Can a task be pre-empted while inside a critical section? Yes, if it is protected by a mutex: the task can be pre-empted, and others trying to enter will block until it resumes and unlocks. That is fine for correctness, but it can cause priority inversion, which is why mutexes have priority inheritance. If the critical section is protected by disabling interrupts or pre-emption (or a spinlock in the kernel), the task cannot be pre-empted there, so such sections must be very short.
Finding races: ThreadSanitizer (-fsanitize=thread), Helgrind, the kernel's KCSAN and lockdep, code review of every shared variable, and stress tests on multi-core hardware. Races are timing-dependent, so "it worked in testing" proves little.