Critical section

On this page 7

A critical section is a region of code that accesses shared mutable state and therefore must not be executed by more than one thread or process at the same time. In concurrency, the critical section is the unit that mutual exclusion protects: as long as at most one execution context is inside it, the operations within it appear indivisible to other threads, and the program avoids race conditions on that state.

The term describes the code, not the tool. A mutex, semaphore, spinlock or monitor is the mechanism that guards the section, while the critical section itself is the stretch of instructions between acquiring and releasing that guard. Designing these regions well is a central skill in programming for multicore systems.

How a critical section enforces mutual exclusion

A critical section works through a protocol of entry and exit. Code before the section runs an entry protocol that waits until the section is free and claims it; code after the section runs an exit protocol that releases the claim so another waiting thread can enter. Everything in between, including reads and writes of shared variables, is serialized.

Classic theory, formulated by Edsger Dijkstra in the 1960s, requires any correct solution to the critical section problem to satisfy three properties. The table lists them together with the failure that occurs when each one is violated.

RequirementMeaningFailure if violated
Mutual exclusionAt most one thread inside at any timeRace condition, corrupted data
ProgressA free section is granted to some waiting threadDeadlock or livelock
Bounded waitingA waiting thread enters after a finite number of othersResource starvation
Correctness requirements for a critical section solution

On modern hardware, a correct critical section also needs memory ordering guarantees. Compilers and CPUs reorder memory operations, so lock implementations include memory barriers with acquire semantics on entry and release semantics on exit. Without them, a thread could enter the section and still see stale values written by the previous owner.

Mechanisms that protect critical sections

Several synchronization primitives can guard a critical section, and they differ mainly in how a waiting thread spends its time and how many threads they admit. The choice depends on expected hold time, contention and whether readers can share access.

MechanismWaiting behaviorBest suited for
MutexBlocks and sleeps in the kernelGeneral-purpose sections of any length
SpinlockBusy-waits on the CPUVery short sections, kernel code
Binary semaphoreBlocks, no ownership trackingSignaling between threads
Read-write lockShared readers, exclusive writersRead-mostly data
Monitor or synchronized blockBlocks, integrated with condition variablesLanguage-level locking in Java or C#
Interrupt disablingPrevents preemption on one coreSingle-core embedded systems
Common guards for critical sections

Language features often hide the entry and exit protocol. Java uses synchronized blocks, C# uses the lock statement, C++ uses std::lock_guard with scope-based release, and Rust ties the protected data to the guard through its generic Mutex type, so the compiler refuses access outside the section. On Windows, the API even has an object type named CRITICAL_SECTION, a lightweight intra-process lock that spins briefly before blocking.

A critical section is a design-level concept, and it is easy to confuse with the primitives and alternatives around it. The comparison below separates the protected region from the tools and the lock-free alternatives.

ConceptRelationship to the critical sectionKey difference
Race conditionThe bug a critical section preventsA failure, not a technique
Atomic operationA hardware-level indivisible stepNo lock, limited to single operations
Lock-free programmingReplaces critical sections with compare-and-swap loopsNo thread can block others
Transactional memoryRuns a section optimistically and retries on conflictSpeculative instead of exclusive
Actor modelAvoids shared state through message passingNo shared section needed
Critical section and neighboring concepts

The important point is that atomicity can be achieved without locking. A single counter increment can use an atomic fetch-and-add, which is faster than a lock-protected section. Multi-variable invariants, however, usually still need a true critical section because no single atomic instruction covers several locations.

Designing efficient critical sections

The governing rule is to keep critical sections short and predictable. While one thread holds the guard, every competing thread waits, so the length of the section directly limits throughput. Amdahl’s law applies: the serialized portion caps the achievable speedup regardless of core count.

  • Move expensive work outside the section: compute first, then lock only to publish the result.
  • Never perform blocking I/O or network calls while holding a lock.
  • Use finer-grained locks for independent data, but only when contention measurably justifies the added complexity.
  • Acquire multiple locks in a fixed global order to prevent deadlock.
  • Release in all paths, including exceptions, by using scope-based guards or try-finally.

Granularity is a trade-off between contention and complexity. One coarse lock is easy to reason about but serializes unrelated work; many fine locks scale better but multiply the risk of ordering mistakes. Profiling lock contention with tools that report wait time is more reliable than guessing.

Common mistakes and failure modes

Most concurrency defects trace back to a critical section that is missing, too wide or inconsistently guarded. The table pairs frequent symptoms with their causes and standard fixes.

SymptomLikely causeFix
Intermittent wrong totalsShared variable accessed outside the sectionGuard every access with the same lock
Program hangsTwo threads take locks in opposite orderEnforce a lock hierarchy
Poor scaling on many coresSection too long or lock too coarseShorten section, split data
Thread never proceedsUnfair lock under heavy contentionUse a fair or queued lock
Latency spikesLock holder preempted or doing I/ORemove blocking calls from the section
Critical section defects, causes and fixes

A subtle error is guarding data with different locks in different places, which provides no mutual exclusion at all. Another is priority inversion, where a low-priority thread holds the section while a high-priority thread waits; real-time systems counter it with priority inheritance protocols.

In plain words

Imagine a single-occupancy restroom with a lock on the door. Anyone can use it, but only one person can be inside at a time, and everyone else waits until the door unlocks.

A critical section is that restroom inside a program. It is the part of the code that touches something shared, such as a bank balance. Letting only one thread in at a time keeps the shared data correct, and keeping the visit short keeps the line from growing.

A real-world example

An online ticketing service runs its booking logic on a server with 32 worker threads. During a popular concert sale, testers notice that the same seat is sometimes sold twice. Investigation shows that two threads both read the seat as available and both write a reservation before either sees the other’s change.

The engineers wrap the check-and-reserve logic for each venue section in a critical section guarded by a per-section mutex, and they move payment authorization outside the lock. The double bookings disappear, and because the guarded code now takes under a millisecond, throughput during the next sale stays close to its previous level.