macro
thread_local! — Give each thread its own value
Declare a thread-local key (LocalKey<T>) with a separate value for each thread. Access through methods such as with; ordinary shared access is provided, so Cell or RefCell allows local mutation. A const initializer may enable a more efficient implementation. Thread-local data is not a shared counter. Result: Declares a LocalKey<T> static item. Expected output (not executed): 'Main: 2, worker: 1\n' Common mistake: Expecting an update in a worker to modify the main thread’s value.
Formal Syntax & Structure
rust syntaxrust
thread_local! { static NAME: Type = initializer; }Working Example
Example Snippetrust
use std::cell::Cell;thread_local! { static VISITS: Cell<u32> = const { Cell::new(0) };}fn main() { VISITS.with(|v| v.set(2)); let worker = std::thread::spawn(|| { VISITS.with(|v| { v.set(v.get() + 1); v.get() }) }).join().unwrap(); println!("Main: {}, worker: {worker}", VISITS.with(Cell::get));}