Section 9.4

Critical section

Definition

A critical section is a part of a program that accesses shared data and must not overlap with certain other code that accesses the same data. Entry and exit steps enclose it, such as locking and unlocking a mutex §9.5 (a lock that one thread holds at a time) or masking interrupts §6.11 (holding them back) on one processor core and unmasking them. The mechanism decides which activities are kept out: a mutex keeps out threads that lock the same mutex, and masking interrupts keeps out interrupt handlers §6.12 on that core only.

The idea

A memory allocator hands out fixed-size blocks from a free list, a chain of unused blocks in which each block holds a pointer to the next one. Handing out a block takes several steps: read the first block and its pointer to the next block, move the head of the list to that next block, and add 1 to a counter of blocks in use. Until the last step, the list and the counter are in a state that no other code may see or change; if another allocation runs in that window, both allocations can take the same block. The code from the first read to the last write is a critical section.

The usual picture is a room with one key. Whoever holds the key is inside, and everyone else waits at the door. The picture is accurate on the point that matters most: the key keeps out only those who come to the door. An activity that never asks for the key walks straight in. Examples are code that skips the lock, an interrupt handler that cannot wait at the door, and a direct memory access §4.36 (DMA) engine, a hardware unit that reads and writes memory by itself. A critical section protects data only against the activities that use its mechanism.

How it works

Designing a critical section takes five steps.

  1. Name the shared data and the invariant that a change breaks for a moment. In the allocator, the list and the counter must agree.

  2. Mark the section, from the first read whose value feeds the change to the last write that restores the invariant.

  3. List every activity that can touch the data: threads on this core, threads on other cores, interrupt handlers at each priority, DMA engines, and readers that take no lock.

  4. Choose a mechanism that keeps all of them out.

  5. Leave the mechanism on every path out of the section, including error returns.

Each mechanism keeps out a different set of activities.

Mutex.

Keeps out threads, on any core, that lock the same mutex. It cannot keep out interrupt handlers, because a handler cannot wait for a lock, and it does not keep out code that skips the mutex.

Scheduler lock.

Stops the scheduler, the part of the operating system that chooses which thread runs, from switching threads on this core. Interrupt handlers still run.

Interrupt masking.

Tells this core to hold back interrupts until they are unmasked. An interrupt that arrives meanwhile stays pending, and its handler runs after the section. On one core, a thread switch happens only from an interrupt or from a call by the running thread, so masking also keeps out other threads on this core, provided the section does not wait, yield or call anything that can switch threads. Masking does not stop other cores, interrupts left above the mask level, or DMA.

Spinlock with interrupt masking.

A spinlock §9.7 is a lock that a waiter acquires by retrying in a loop instead of sleeping. Taken with interrupts masked, it keeps out threads and interrupt handlers on every core that take the same spinlock.

Handoff rule for hardware.

None of the mechanisms above stops a DMA engine. Software keeps the engine and the processor apart by a rule: the processor stops touching a buffer when it starts a transfer, and touches it again only after the transfer reports completion.

Readers need the same analysis. A reader that takes no lock is not kept out of anything. A design that deliberately lets readers run without a lock, such as read-copy update §9.20 (RCU), must instead ensure that every reader sees either the complete old state or the complete new state, a coherent snapshot §9.23.

On Arm Cortex-M processors, two registers in the core control interrupt masking. Arm calls every event that diverts the processor, interrupts included, an exception, and gives each exception a priority.

Operating systems wrap these registers. In Zephyr §6.33, a real-time operating system for small devices, irq_lock() masks interrupts and returns a key that records whether they were already masked, and irq_unlock(key) restores exactly that earlier state, so one masked section may run inside another. Recent Zephyr documentation names k_irq_lock() as the preferred spelling of the same call. On Cortex-M cores that have BASEPRI, Zephyr’s lock raises BASEPRI instead of setting PRIMASK. Interrupts configured above that level, which Zephyr calls zero-latency interrupts, are never held back; in return, their handlers must not call the kernel or change data that kernel code reads. Zephyr’s documentation also forbids a thread to sleep while it holds the interrupt lock.

Worked example

A pool hands out 32-byte blocks. Its free list is head →\to X →\to Y →\to Z, and the counter used is 0. A thread and an interrupt handler both allocate from the pool. Without a critical section, this order can occur:

  1. The thread reads head, which points to X, and reads X’s pointer to the next block, Y.

  2. An interrupt arrives. The handler reads head, which still points to X, sets head to Y, sets used to 1, and takes X.

  3. The thread resumes, sets head to Y, sets used to 2, and takes X.

Both now use block X and will overwrite each other’s data. The counter says 2 blocks are in use while only one block has left the list. Two invariants are broken at once.

The repair masks interrupts from step 1 until the thread has updated used. The interrupt now stays pending until the thread has set head to Y and used to 1. The handler then reads head, which points to Y, takes Y, sets head to Z and sets used to 2. Each caller has its own block, and the counter matches the list.

Every interrupt that arrives during the section pays for the masking. Suppose the core runs at 64 million cycles per second and the section takes 64 cycles. It lasts 64/(64×106)64 / (64 \times 10^{6}) s, which is 1 microsecond, so a held-back handler starts up to 1 microsecond late. Suppose a later change adds a call to a logging function of 640 cycles inside the section. The section now takes 64+640=70464 + 640 = 704 cycles, which is 704/64=11704 / 64 = 11 microseconds. Take a radio interrupt that must be handled within 5 microseconds of arriving, and ignore the few cycles the processor needs to start a handler. If the interrupt arrives tt microseconds after the section starts, its handler starts 11−t11 - t microseconds late, which exceeds 5 whenever t<11−5=6t < 11 - 5 = 6. There are two repairs: move the work that does not touch the pool, here the logging, out of the section; or leave that one interrupt above the mask level, in which case its handler must never touch the pool.

Masking does not help against hardware. If the thread frees a block that a DMA engine is still filling, the engine keeps writing into it after the next allocation has handed it out. Only a handoff rule, free a block only after its transfer has completed, prevents this.

Stated precisely

Edsger Dijkstra posed the critical-section problem in 1965 [292]. Operating-systems textbooks state its requirements as three properties of the entry and exit steps around each participant’s critical section:

  1. Mutual exclusion: at most one participant is inside its critical section at any time.

  2. Progress: if no participant is inside and some want to enter, one of them enters within finite time.

  3. Bounded waiting: once a participant has asked to enter, the number of times other participants enter before it is bounded.

A participant is an activity that executes the entry and exit steps. The guarantee says nothing about any other activity.

For a given mechanism, let SS be the set of activities that enter through it. The mechanism guarantees that the critical sections of any two members of SS never overlap in time. The invariant of the shared data is protected when every activity that can change the data, or read it while it is inconsistent, either belongs to SS or is kept off the data by a separate rule, such as the handoff rule for DMA.

Limits and common mistakes

Masking interrupts delays every masked interrupt by up to the length of the section, so such sections must be short, bounded and free of waiting.

Restore the earlier state instead of unmasking blindly. A section that ends by enabling all interrupts breaks an outer section that had them masked; the saved key or register value avoids this.

Too small a section causes race conditions §9.2: the check and the action of a check-then-act operation must lie in one section. Too large a section makes others wait, and a section that takes a second lock can cause deadlock §9.14, in which activities wait for each other forever, unless all code takes locks in one fixed order, which is called lock ordering §9.15.

If a low-priority thread holds a lock and a medium-priority thread preempts it, a high-priority thread waiting for the lock waits for the medium-priority thread as well. This is priority inversion §9.16.

Exclusion is not visibility. Masking interrupts on one core does not make that core’s writes visible to another core or to a DMA engine in any defined order; that needs memory barriers §4.37 and, on processors with data caches, cache maintenance. A correct mutex implementation includes the ordering that the threads using it need.

A section that only reads is still needed when another activity writes. A reader that sees half of an update can read a count and a pointer that do not belong together.

Questions answered

Which contexts does the exclusion cover: threads, interrupts, DMA, or readers?

The exclusion covers only the contexts that enter through the same mechanism and that the mechanism can actually stop; no single mechanism covers all four. A critical section is code that touches shared data and must not overlap with certain other code, and the mechanism that guards it decides which other code is kept out:

For each critical section, write down which of these contexts can touch the data, and check that the chosen mechanism covers every one of them.

Related entries: Mutex (§9.5), Coherent snapshot (§9.23), Direct memory access (DMA) (§4.36), Spinlock (§9.7), Race condition (§9.2), Interrupt service routine (ISR) (§6.12). Further reading: [6, 176, 292].