expression
Stop at a safe boundary when cancellation is requested
Cancellation is cooperative: check a shared flag between independent units of work. This deterministic fixture requests cancellation after two units in one thread. Relaxed ordering suffices for this flag alone; it does not publish other shared data. In a real application, an event adapter sets the flag, and blocking work may delay observation. Fixture: Expected stdout (not executed): completed=2, cancelled=true Expected stderr: (empty) Expected exit: 0 Common mistake: Assuming a cancellation flag forcibly interrupts every operation or undoes earlier writes.
Formal Syntax & Structure
rust syntaxrust
cancel.load(Ordering::Relaxed)Working Example
Example Snippetrust
fn main() { use std::sync::atomic::{AtomicBool, Ordering}; let cancel = AtomicBool::new(false); let mut completed = 0; for _ in 0..5 { if cancel.load(Ordering::Relaxed) { break; } completed += 1; if completed == 2 { cancel.store(true, Ordering::Relaxed); } } println!("completed={completed}, cancelled={}", cancel.load(Ordering::Relaxed));}