Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Macros

Rust thread_local! macro

Reference for the Rust thread_local! macro: declaring per-thread statics, LocalKey with, set, get and take, lazy initialization, const init and destructors.

thread_local! declares one or more static variables whose value exists separately in every thread. Each thread gets its own copy, created the first time that thread touches it. The variable has the type LocalKey<T>, and you reach the value through methods rather than directly.

Because each thread owns its copy, no locking is needed, but you often wrap the value in Cell or RefCell to change it, since access is through a shared reference.

Rust
thread_local! {
    static COUNTER: Cell<u32> = const { Cell::new(0) };
}

Try it

Rust Each thread has its own copy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust RefCell, set/get helpers and lazy init

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
thread_local! {
    [pub] static NAME: Type = initializer;
    [pub] static OTHER: Type = const { const_initializer };
}
Item Description
LocalKey::with(f) Runs f with &T. Panics if the value is being or has been destroyed.
try_with(f) Like with, but returns Err(AccessError) instead of panicking.
Cell keys: get, set, take, replace Direct access for LocalKey<Cell<T>>.
RefCell keys: with_borrow, with_borrow_mut, set, take, replace Direct access for LocalKey<RefCell<T>>.

Panics: with and the helpers panic if called while the thread-local is being destroyed, and with_borrow_mut panics if the RefCell is already borrowed.

Usage notes

  • Lazy by default. The initializer runs on first access in each thread. The const { ... } form is evaluated at compile time, avoids the check on every access, and is faster; use it when the initializer is a constant expression.
  • Destructors run when a thread exits (best effort; not guaranteed in every platform case, and not for the main thread on process exit).
  • No Sync needed. Because the value never leaves its thread, it can be a non-thread-safe type such as Rc.
  • Not shared. Threads cannot see each other's values, so this is wrong for a shared counter; use an atomic or Mutex for that.
  • Spawned threads start fresh. They do not inherit the parent's value.
  • Avoid in async code unless you know which thread polls the task; tasks can move between threads.