std-type
LocalKey: per-thread values
Each thread accesses its own initialized value through the key. A Cell can support mutation inside one thread without sharing the cell across workers. The borrow supplied to with cannot escape its closure. Expected stdout (not executed): 9 5 Common mistake: Expecting a thread-local counter to be a process-wide counter.
Formal Syntax & Structure
rust syntaxrust
thread_local! { static KEY: Cell<T> = ...; }; KEY.with(F)Working Example
Example Snippetrust
fn main() { use std::cell::Cell; thread_local! { static COUNT: Cell<u32> = const { Cell::new(0) }; } COUNT.with(|c| c.set(5)); let worker = std::thread::spawn(|| COUNT.with(|c| { c.set(9); c.get() })); println!("{} {}", worker.join().unwrap(), COUNT.with(|c| c.get()));}