Critical Sections
Code that must run as if atomic with respect to other threads touching the same data.
Level: intermediate
What is it?
A critical section is a region of code that accesses shared state and must preserve an invariant against concurrent operations. The section itself is defined by the state it protects, not by its size or a special syntax keyword.
Why does it matter?
Many race bugs occur because a multi-step change is interrupted halfway through. Identifying the critical section makes the invariant explicit and helps select a lock, atomic operation, or other coordination mechanism.
Mental model
Imagine two workers editing one ledger. The critical section is not every line in the program; it is the minimum operation on shared state that must appear indivisible to other workers.
How it works
- Mutual exclusion prevents two participants from executing the protected region simultaneously.
- Correctness depends on protecting every access that can violate the same invariant, including reads when required.
- Progress means a thread that can safely enter should not be postponed forever by the protocol.
- Bounded waiting limits how many times others can enter before a waiting thread gets its turn; not every mutex guarantees strict fairness.
- Reducing critical-section duration limits contention, but moving operations outside the lock must not break the invariant.
Steps
- Identify the shared state and write down the invariant it must satisfy.
- Find the complete read-modify-write sequence that can violate it.
- Protect that sequence with a suitable lock or atomic operation.
- Stress-test concurrent access and use a race detector where available.
Real-world usage
- Protecting shared counters, queues, maps, and account balances.
- Reviewing concurrent code for unprotected reads or state changes.
- Explaining mutual exclusion, progress, and bounded-waiting requirements.
Common mistakes
- Locking only the final write while leaving the dependent read outside the lock.
- Making a critical section so large that unrelated work waits unnecessarily.
- Assuming that one successful stress test proves race freedom.
Interview questions
What defines a critical section?
It is the code region that accesses shared state and must preserve an invariant against concurrent interleavings.
Does a mutex alone guarantee bounded waiting?
Not necessarily. A mutex provides mutual exclusion, but fairness and starvation behavior depend on the specific primitive and protocol.