ownership

Rust Thread-local Cell

Thread-local storage gives each thread its own payload rather than a shared global counter. A closure passed to with accesses the current thread’s cell. Thread-local data does not solve synchronization for genuinely shared data. Expected output (not executed): 8 3 Why: Joining the worker fixes output order; its counter is distinct from the main thread’s. Common mistake: Expecting a thread-local counter to accumulate all threads’ calls.

Formal Syntax & Structure

rust syntaxrust
thread_local! { static COUNT: Cell<u32> = Cell::new(0); }

Working Example

Example Snippetrust
use std::{cell::Cell, thread};thread_local! { static COUNT: Cell<u32> = Cell::new(0); }fn main() {    COUNT.with(|n| n.set(3));    let other = thread::spawn(|| COUNT.with(|n| { n.set(8); n.get() })).join().unwrap();    println!("{other}");    COUNT.with(|n| println!("{}", n.get()));}
Rust Reference