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?
answer
- tasks are interrupt handlers
- a ceiling per resource, at compile time
- lock raises BASEPRI, not PRIMASK
- local means one task, no lock
- no await inside the closure
basics
~20 sRTIC 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.
solid answer
~40 sAn RTIC 2 app declares resources in `#[shared]` and `#[local]` structs that `#[init]` returns. A local resource is listed by one task and arrives as `&mut` with no locking; a second task listing it is a compile error. A shared resource that a task may mutate arrives as a proxy implementing `rtic::Mutex`: dereferencing it fails with E0614, so even the priority-2 button task must call `lock`. RTIC knows every task's static priority and resource list, so it computes each resource's ceiling at compile time, here 2. `lock` raises the system ceiling to 2 for the closure, on Armv7-M by writing BASEPRI, so the button cannot start while idle holds the counter, yet a priority-3 task that never touches it still preempts. That is the Stack Resource Policy: race-free, deadlock-free, one shared stack.
code
rust · 46 lines#![no_std]
#![no_main]
#[rtic::app(device = pac, peripherals = false)]
mod app {
#[shared]
struct Shared {
presses: u32,
}
#[local]
struct Local {
edges: u32,
}
#[init]
fn init(_cx: init::Context) -> (Shared, Local) {
(Shared { presses: 0 }, Local { edges: 0 })
}
// priority 0: lowest, runs when nothing else is pending
#[idle(shared = [presses])]
fn idle(mut cx: idle::Context) -> ! {
loop {
let n = cx.shared.presses.lock(|p| core::mem::replace(p, 0));
crate::report(n);
}
}
// a hardware task: the EXTI0 interrupt, priority 2
#[task(binds = EXTI0, priority = 2, shared = [presses], local = [edges])]
fn button(mut cx: button::Context) {
*cx.local.edges += 1; // only this task owns it: no lock
cx.shared.presses.lock(|p| *p += 1);
}
}
#[inline(never)]
fn report(n: u32) {
unsafe { core::ptr::write_volatile(0x2000_1000 as *mut u32, n) };
}
#[panic_handler]
fn panic(_: &core::panic::PanicInfo) -> ! {
loop {}
}go deeper
Recall that RTIC tasks are interrupt handlers with priorities, that #[local] needs no lock and #[shared] goes through lock.
Explain the ceiling: the highest priority of any task using a resource, computed at compile time, and what lock does with it.
Show that lock blocks only tasks at or below the ceiling, explain BASEPRI versus NVIC masking on Armv6-M, and the E0614 and E0728 errors RTIC turns mistakes into.
Judge when SRP's compile-time guarantees justify RTIC's model of static priorities, run-to-completion tasks and a single core.
## The RTIC model in one paragraph **RTIC** (Real-Time Interrupt-driven Concurrency) has no software kernel; its developers describe it as a hardware-accelerated RTOS. An app is a module annotated `#[rtic::app(device = ...)]` that names the chip's peripheral access crate. Inside it: an `#[init]` function that runs once with interrupts disabled and returns the initial resources; an optional `#[idle]` function at priority 0 that runs when nothing else is pending; **hardware tasks**, functions bound to an interrupt vector with `#[task(binds = EXTI0, priority = 2, ...)]`; and **software tasks**, `async fn`s run by executors that RTIC generates on spare interrupts listed in `dispatchers = [...]`. The NVIC itself schedules hardware tasks by priority, so there is no software scheduler and no time slicing. A hardware task defaults to priority 1 and may not be 0; a software task defaults to 0. ## Local versus shared resources Resources are fields of two structs: - **`#[local]`**: owned by exactly one task, which lists it as `local = [edges]` and receives `&mut` to it with no locking. If two tasks list the same local, RTIC rejects the app: "Local resource "edges" is used by multiple tasks or collides with multiple definitions". - **`#[shared]`**: reachable from several tasks, each listing it as `shared = [presses]`. The task's context does not hold `&mut u32`; it holds a generated proxy type that implements the `rtic::Mutex` trait. Trying to bypass the proxy with `*cx.shared.presses += 1` fails with **E0614**, "type `presses_that_needs_to_be_locked<'_>` cannot be dereferenced". This holds even in the highest-priority task that uses the resource: in RTIC 2 a shared resource that any task mutates is reached only through `lock(|p| ...)`. Read-only access, listed as `shared = [&presses]`, hands out `&T` without a lock, and RTIC allows it only when no task takes the resource exclusively. ## What `lock` actually does RTIC is built on the **Stack Resource Policy** (SRP). Because every task's priority and resource list is written in the app, the macro computes at compile time each resource's **ceiling**: the highest priority of any task that uses it. For `presses`, used by idle (0) and the button task (2), the ceiling is 2. 1. On entry, `lock` raises the system ceiling to the resource's ceiling. On Armv7-M and later it writes the **BASEPRI** register (the generated code uses `msr basepri_max`), which masks interrupts at that priority and below. 2. The closure runs with `&mut u32`; no task that could touch `presses` can start. 3. On exit, the previous BASEPRI is restored, and any pended button interrupt runs immediately. Interrupts above the ceiling are untouched, which is the advantage over a global critical section: a priority-3 motor-control task that never uses `presses` keeps its latency while idle holds the counter. When a ceiling equals the highest priority the hardware has, RTIC falls back to a critical section. On Armv6-M, which has no BASEPRI, the `thumbv6-backend` feature instead clears the NVIC enable bits of the affected interrupts, using masks computed at compile time. | Mechanism | What it blocks | Cost | |---|---|---| | `critical_section::with` | every maskable interrupt | latency for all handlers | | RTIC `lock`, Armv7-M | tasks at or below the ceiling | a few instructions on BASEPRI | | RTIC `lock`, Armv6-M | the interrupts at or below the ceiling | masking NVIC enable bits | | `#[local]` access | nothing | none | ## Rules the compiler enforces - **No `.await` while holding a resource.** `lock` takes a synchronous closure, so `.await` inside it is **E0728**, "`await` is only allowed inside `async` functions and blocks". The RTIC book notes this preserves SRP's requirement that locks are released in LIFO order. Copy the value out, end the lock, then await. - **`#[lock_free]`** on a shared field gives tasks direct `&mut` access without `lock`, but only when every task that uses it runs at the same priority, so none can preempt another, and never from async software tasks. Mixing priorities is rejected: "Lock free shared resource "presses" is used by tasks at different priorities". - Nested locks follow the closure nesting, so they are always released in LIFO order and cannot deadlock. ## Applying it to the counter Idle reads and resets inside one lock with `core::mem::replace(p, 0)`; the button task increments inside its own lock and keeps a per-task `edges` count as a local resource with no lock at all. The whole app contains no `unsafe` and no `static mut`; RTIC's generated code holds the resources in internal statics and hands out references only in the pattern SRP proves sound. The model is single-core: RTIC describes an app as a system model for single-core applications.
- What does `#[lock_free]` on a shared resource allow, and when does RTIC reject it?It removes the `lock` call: tasks get `&mut` (or `&`) directly. That is sound only when every task using the resource has the same priority, because equal-priority tasks run to completion without preempting each other. RTIC rejects it when the users have different priorities, and whenever an async software task uses it.
- Why can an RTIC 2 async software task not `.await` while holding a lock?`lock` takes a synchronous `FnOnce`, so an `.await` inside the closure is E0728. That is by design: SRP needs resources released in LIFO order and the ceiling restored before other work can be scheduled. Copy what you need out of the resource, let the lock end, then await, and lock again afterwards if necessary.
- How does a `lock` differ on a Cortex-M0 with RTIC's `thumbv6-backend`?Armv6-M has no BASEPRI register, so RTIC implements the ceiling by clearing the NVIC enable bits of every interrupt at or below the resource's ceiling, then restoring them, using masks it computes at compile time. The guarantees are the same; the cost is updating NVIC enable masks, with barriers, instead of one BASEPRI write, and RTIC must know every bound interrupt to build the masks.
- Every RTIC lock disables all interrupts, just like a global critical section.
- The highest-priority task may dereference a mutable shared resource without lock.
- Two tasks can list the same #[local] resource if they run at different priorities.
- RTIC schedules tasks in a software kernel with time slicing.
- An async software task should hold the lock across .await to keep the count consistent.
- A hardware task can run at priority 0 alongside idle.