critical-section provides a portable Rust abstraction for entering a critical section and running code while shared state is protected from concurrent interrupt access. Its API supplies a temporary permission token; shared data can be accessed only while that token remains in scope. section 1.4.4 section 4.6.6
Use a critical section when:
- Main code and an interrupt handler access the same peripheral or state. section 1.4.4
- A peripheral must be moved into global storage once and later borrowed mutably from multiple contexts. section 4.6.5
- Direct interrupt disabling would expose unsafe restoration behavior; the abstraction scopes access and restores the permission boundary when the closure ends. section 4.5.5 section 1.4.4
Sharing a timer peripheral
Store the peripheral as Mutex<RefCell<Option<SYST>>>. During initialization, enter a critical section and replace the empty Option with the owned peripheral. Later, enter another critical section before borrowing and mutating it from an interrupt handler. This prevents double initialization, undefined access, and races. section 4.6.5
use cortex_m::interrupt::{Mutex, free};
use core::cell::RefCell;
use cortex_m::peripheral::SYST;
use core::ops::DerefMut;
static G_SYST: Mutex<RefCell<Option<SYST>>> = Mutex::new(RefCell::new(None));
fn main() -> ! {
let dp = cortex_m::Peripherals::take().unwrap();
// Transfer ownership into the static global using .replace()
in a critical section
free(|cs| {
G_SYST.borrow(cs).replace(Some(dp.SYST));
});
loop {
cortex_m::asm::wfi();
}
}
#[exception]
fn SysTick() {
free(|cs| {
if let Some(ref mut syst) = G_SYST.borrow(cs).borrow_mut()
.deref_mut() {
let _ = syst.has_wrapped();
}
});
}
Shows a complete shared-peripheral pattern, including ownership transfer into static storage and protected access from SysTick. section 4.6.5
[dependencies.cortex-m] version = "*" features = ["critical-section-single-core"]
Shows the Cortex-M Cargo feature needed to provide the single-core critical-section implementation. section 4.6.6
