skip to content

Interrupts and Shared State

Sharing data between main code and an interrupt handler needs a critical section, not static mut. Interviewers ask how RTIC and Embassy structure firmware concurrency.

on this pageshow

questions

5

In Rust firmware, how do you share a button-press counter between a Cortex-M interrupt handler and the main loop using `critical_section::Mutex<RefCell<u32>>`?

level: middleimportance: must knowfreq 40%

answer

  1. a static must be Sync
  2. the Mutex adds Sync, not mutability
  3. a token proves interrupts are off
  4. RefCell checks the &mut at run time
  5. read and reset in one section

basics

~20 s

Declare static PRESSES: Mutex<RefCell<u32>>; the handler and the main loop each enter critical_section::with(|cs| ...), which on a single-core Cortex-M disables interrupts, and borrow the counter with the cs token. Main reads and resets it with PRESSES.replace(cs, 0).

solid answer

~40 s

A `static` must be `Sync`, and `RefCell<u32>` is not, so rustc rejects it with E0277. `critical_section::Mutex<T>` is `Sync` whenever `T: Send`, but it only hands out `&T` to code that holds a `CriticalSection` token, and the only safe way to get one is `critical_section::with`. What that call does is chosen by the binary: on a single-core Cortex-M, the `cortex-m` crate's `critical-section-single-core` feature saves PRIMASK and disables interrupts. Inside the closure the handler does `*PRESSES.borrow_ref_mut(cs) += 1`, and the main loop does `PRESSES.replace(cs, 0)`, so reading and resetting happen as one step the handler cannot split. The `Mutex` itself gives no mutability; `RefCell` adds it with a run-time borrow check, and for a `Copy` counter `Cell<u32>` would do.

code

rust · 33 lines
rust
#![no_std]
#![no_main]

use core::cell::RefCell;
use cortex_m_rt::entry;
use critical_section::Mutex;
use pac::interrupt;

static PRESSES: Mutex<RefCell<u32>> = Mutex::new(RefCell::new(0));

#[interrupt]
fn EXTI0() {
    // clear the button's pending flag in the EXTI peripheral here
    critical_section::with(|cs| *PRESSES.borrow_ref_mut(cs) += 1);
}

#[entry]
fn main() -> ! {
    unsafe { cortex_m::peripheral::NVIC::unmask(pac::Interrupt::EXTI0) };
    loop {
        // read and reset in one critical section, so no press is lost
        let n = critical_section::with(|cs| PRESSES.replace(cs, 0));
        report(n);
        cortex_m::asm::wfi();
    }
}

fn report(_n: u32) {}

#[panic_handler]
fn panic(_: &core::panic::PanicInfo) -> ! {
    loop {}
}

go deeper

for a junior

Recall that a static shared with an interrupt handler must be Sync, and that critical_section::with plus a Mutex<RefCell<T>> is the safe way to reach it.

for a middle

Explain why the Mutex only adds Sync, why RefCell supplies the mutation, and why main must read and reset inside a single critical section.

for a senior

Show you know where the implementation comes from: one provider per binary, the link error when it is missing, and why single-core implementations are wrong on a dual-core part.

for a principal

Weigh critical sections against their cost: every one delays all maskable interrupts, so a codebase full of them trades simplicity for latency and jitter you must budget.

## The problem: one counter, two contexts A button wired to an external-interrupt line raises the `EXTI0` interrupt on every press. The **interrupt handler** has no arguments and no return value, and it is invoked by the hardware, not called by `main`, so it cannot receive a reference to anything. The only state it can reach is a `static`. The main loop must read that same `static`, report the count and reset it to zero. Rust requires every `static` to be **`Sync`**, because a static is reachable from any thread of execution, and the Rust embedded book treats an interrupt handler as exactly that: a separate thread that may run between any two instructions of `main`. A plain `static PRESSES: RefCell<u32>` therefore fails with **E0277**, "`RefCell<u32>` cannot be shared between threads safely", even in a `#![no_std]` crate. Making it `static mut` instead compiles, but moves the whole proof of correctness into `unsafe` blocks; the material on `static mut` covers why that is the wrong tool. ## What `critical_section::Mutex` does, and what it does not The `critical-section` crate provides one universal API for a **critical section**, a region in which nothing else that touches the protected data can run. Its `Mutex<T>` has three properties worth knowing exactly: - It implements `Sync` for any `T: Send`, which is what lets it sit in a `static`. - `borrow(cs)` returns `&'cs T` and requires a `CriticalSection<'cs>` token, so the data is reachable only while a critical section is open. - It provides **no interior mutability** of its own. The crate's documentation explains why: tokens are `Copy` and critical sections may nest, so returning `&mut T` would let two borrows alias. Mutation therefore comes from the cell inside. `RefCell<T>` adds a run-time borrow flag, so `borrow_ref_mut(cs)` (the crate's shortcut for `borrow(cs).borrow_mut()`) yields a unique `RefMut`, and a second overlapping mutable borrow panics instead of aliasing. For a `Copy` value such as `u32`, `Cell<u32>` is enough and has no flag. `RefCell` earns its place when the shared value is not `Copy`, for example a peripheral or pin moved in at start-up as an `Option<T>`. ## The counter, end to end 1. Declare `static PRESSES: Mutex<RefCell<u32>> = Mutex::new(RefCell::new(0));` (both constructors are `const fn`). 2. In the handler, enter `critical_section::with(|cs| *PRESSES.borrow_ref_mut(cs) += 1)`. 3. In the main loop, read and reset in **one** critical section: `critical_section::with(|cs| PRESSES.replace(cs, 0))`. 4. Do the slow work, such as formatting or transmitting the count, **after** the closure returns, with interrupts enabled again. Step 3 is the point of the exercise. Reading in one critical section and storing zero in a second leaves a gap in which the handler can run, and its press is erased by the store. ## Where the critical section comes from `critical_section::with` calls two functions, `acquire` and `release`, that the crate only declares. Exactly one crate in the final binary must define them: | Implementation | What it does | |---|---| | `cortex-m`, feature `critical-section-single-core` | Saves PRIMASK, disables interrupts on the one core, restores PRIMASK on exit | | A multicore HAL's implementation (for example `rp2040-hal`'s `critical-section-impl` feature) | Disables interrupts on the current core and takes a hardware spinlock | | `critical-section` itself, feature `std` | A global `std::sync::Mutex`, for host-side tests | If no crate provides one, the link fails with undefined symbols `_critical_section_1_0_acquire` and `_critical_section_1_0_release`; two providers also fail to link. A **library** crate depends on `critical-section` and enables no implementation, leaving the choice to the firmware binary. Older code uses `cortex_m::interrupt::free(|cs| ...)` with `cortex_m::interrupt::Mutex`, the same idea tied to Cortex-M. ## Costs and limits - While the closure runs, every maskable interrupt waits, so a long critical section adds **latency and jitter** to every handler in the system. Keep the closure to a few loads and stores. - Disabling interrupts does not stop the non-maskable ones (NMI, HardFault); `cortex-m-rt` documents that their handlers must not touch data guarded this way. - The single-core implementation does nothing about a second core. On a dual-core chip the same code is sound only with a multicore implementation. - Nesting is allowed: an inner `critical_section::with` is mostly a no-op inside an outer one. ## Common mistakes - Expecting `Mutex<u32>` to be mutable: it is not; the cell provides mutation. - Splitting read and reset across two critical sections and losing presses. - Enabling `critical-section-single-core` inside a reusable driver crate, which forces that choice on every board that uses it. - Holding a `RefMut` from `borrow_ref_mut` while calling code that borrows the same cell again, which panics.

  • What happens if the firmware depends on `critical-section` but no crate provides an implementation?
    The build compiles and then fails to link: rust-lld reports undefined symbols `_critical_section_1_0_acquire` and `_critical_section_1_0_release`. The crate only declares those functions; one crate in the binary must define them, such as `cortex-m` with `critical-section-single-core` or a HAL's multicore implementation. Two providers fail to link as well, which is why libraries should enable none.
  • Is the same code sound on a dual-core microcontroller?
    Only if the binary links a multicore implementation. `cortex-m`'s single-core one disables interrupts on the current core only, so the other core could still touch `PRESSES`. A dual-core chip's HAL supplies an implementation that also takes a hardware spinlock, such as the one `rp2040-hal` offers behind its `critical-section-impl` feature. The counter code itself does not change.
  • When would `Mutex<Cell<u32>>` be the better choice here?
    For a `Copy` value like this counter. `Cell` only moves values in and out (`get`, `set`, `replace`), so `PRESSES.borrow(cs).replace(0)` works with no run-time borrow flag and no panic path. `RefCell` is needed when you must hand out `&mut T` to a non-`Copy` value, such as a peripheral struct moved into an `Option` after start-up.

  • critical_section::Mutex makes the counter mutable without a Cell or RefCell inside.
  • The handler can borrow the RefCell without a token because main cannot preempt it.
  • critical_section::with always stops every core of a multicore chip.
  • A reusable driver crate should enable cortex-m's critical-section-single-core feature itself.
  • A plain static RefCell compiles in no_std firmware because there are no threads.
  • Formatting and sending the count inside the critical section costs nothing.
open as a page

In Rust 2024 firmware, a `static mut PRESSES: u32` shared with a button interrupt compiles without warnings, yet the release build hangs; why, and what is the fix?

level: seniorimportance: must knowfreq 35%

basics

~20 s

Main and a preempting handler access it without synchronisation, a data race, so the optimiser loads PRESSES once and spins on that copy. Use a plain static PRESSES: AtomicU32: fetch_add in the handler, swap(0, ..) in main, or a critical section.

open as a page

In Embassy firmware, how does a task wait for a button interrupt without polling, and which `embassy_sync` raw mutex must the shared `Signal` use?

level: seniorimportance: should knowfreq 24%

basics

~10 s

The task awaits PRESSED.wait(); the executor sleeps on WFE until the #[interrupt] handler calls PRESSED.signal(()), which wakes it. A Signal touched from a handler needs CriticalSectionRawMutex: ThreadModeRawMutex panics there and NoopRawMutex is not Sync.

open as a page

In an RTIC 2 app, how do `#[shared]` and `#[local]` resources, task priorities and `lock` stop a button task and the idle loop racing on a press counter?

level: seniorimportance: should knowfreq 25%

basics

~20 s

RTIC computes each shared resource's ceiling, the highest priority of any task using it; lock raises the system priority to that ceiling, so no task touching the counter can preempt. A #[local] resource belongs to one task and needs no lock.

open as a page

As a Rust firmware lead, how do you choose between bare interrupt handlers with critical sections, RTIC 2 and an Embassy async executor for a new product?

level: principalimportance: should knowfreq 22%

basics

~20 s

Choose by latency budget, I/O complexity and ecosystem. Bare handlers suit small firmware; RTIC 2 suits hard priorities, with hardware-scheduled tasks and compile-time lock ceilings; Embassy suits I/O-heavy products, with async drivers but cooperative scheduling within each executor.

open as a page