Skip to content
Tutorials Center
My learning

Topics

Lesson 81 of 132 ยท Concurrency

thread_local!, OnceLock and LazyLock

Learn safe global state in Rust: thread_local! with Cell and RefCell, OnceLock for set-once config, LazyLock for lazy statics, LazyCell, and why static mut is a trap.

Sooner or later a program wants something that looks global: a configuration loaded once, a table that is expensive to build, a counter that every function can bump, a cache. Many languages let you declare a mutable global and move on. Rust makes you say who may touch it and from which threads, because a plain shared mutable global is a data race waiting to happen.

The good news is that the standard library has a small toolbox for each situation. thread_local! gives every thread its own private copy. OnceLock holds a value that is set exactly once. LazyLock builds a value the first time anyone looks at it. Their single-threaded cousins OnceCell and LazyCell do the same without any locking. This lesson shows when to reach for each, and how they combine with Mutex and RwLock and atomics when the global must also change.

The problem with globals

A static item lives for the whole program and is shared by every thread. Rust therefore requires its type to be Sync, and you cannot mutate it through a plain static. The old escape hatch, static mut, needs unsafe on every access and is a data race the moment two threads use it (see Unsafe Rust). Modern code almost never needs it.

flowchart TD
    A["I need global-looking state"] --> B{"Shared between threads?"}
    B -->|"No, one copy per thread"| C["thread_local!"]
    B -->|"Yes"| D{"Does it change after setup?"}
    D -->|"No"| E{"Value known at startup?"}
    E -->|"Built on first use"| F["LazyLock"]
    E -->|"Supplied at run time"| G["OnceLock"]
    D -->|"Yes"| H["LazyLock or static wrapping<br/>Mutex, RwLock or an atomic"]

Pick the tool by asking: per thread or shared, and does it change after it is set up.

thread_local!: one value per thread

The thread_local! macro declares a value that is created separately for each thread, the first time that thread touches it. No other thread can see it, so no locking is needed and the value does not even have to be Sync.

You cannot get a plain reference out of a thread-local, because the value might be destroyed when its thread ends. Instead you borrow it inside a closure with with.

Rust Each thread sees its own counter

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.

The const { ... } form is an optimization: when the initial value can be computed at compile time, the compiler skips the lazy-initialization check on each access. Use it whenever you can.

A LocalKey<Cell<T>> has convenient shortcuts so you do not need with for simple values: get, set, take and replace (the last two need T: Default or return the old value). For a LocalKey<RefCell<T>> there are with_borrow, with_borrow_mut, set, take and replace.

Rust RefCell in a thread-local: a per-thread log

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.

Typical uses and limits

Thread-locals suit data that is naturally per thread: a reusable scratch buffer that saves allocations, a per-thread random number generator, a "current request id" for log lines, or a cache that never needs to be coordinated. They are a poor fit for anything you want worker threads to share results through, since each thread only sees its own copy.

Two details to remember:

  • Destructors run at thread exit for values with a Drop implementation, but the order is not specified, and a thread-local accessed during another thread-local's destruction can fail. try_with returns an error instead of panicking in that case.
  • std::thread::scope and thread pools reuse threads. In a pool, a thread-local persists across tasks run by the same worker, so do not assume it is fresh for each job.
Rust Drop runs when the thread ends

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.

OnceLock: set once, read forever

OnceLock<T> is a cell that starts empty and can be filled exactly once, from any thread. After that it hands out &T for free. It is the right tool for configuration discovered at startup, because static initializers must be computable at compile time and real configuration is not.

Rust A global config set once

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.

get_or_init runs its closure at most once, even if many threads race to call it; the losers wait and then see the winner's value. set returns Err(value) if the cell is already full, get returns an Option<&T>, and into_inner/take are available when you own the cell.

LazyLock: a static that builds itself

LazyLock<T> is a OnceLock that remembers its initializer. You declare a static, give it a closure, and the closure runs the first time anything dereferences the static. It lets you have a static whose value needs allocation, parsing or other run-time work.

Rust A lookup table built on first use

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.

The table is built once, on the first call, and the message appears only once. If the closure panics, the lazy value is poisoned and later accesses panic too, so keep initializers simple and infallible.

A mutable global the safe way

A LazyLock or a static is immutable. To change shared global state, put interior mutability inside: a Mutex or RwLock for anything complex, an atomic for a single number. Mutex::new is a const fn, so you often do not even need LazyLock.

Rust A global registry behind a Mutex

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.

We print the names without ids because which thread gets which id depends on scheduling. Always make your output independent of thread order when you test concurrent code.

OnceCell and LazyCell: the single-threaded versions

std::cell::OnceCell and std::cell::LazyCell have the same API as their Lock siblings but are not Sync, so they cannot sit in an ordinary static. They cost nothing for synchronization and fit fields inside a struct, or values behind a thread_local!.

Rust LazyCell for a field computed on demand

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.

Choosing between them

Need Use
A private value per thread thread_local!
Global filled in at startup, then read-only OnceLock
Global computed on first use, then read-only LazyLock
Global that changes Mutex, RwLock or an atomic in a static
Lazy or set-once value inside one thread LazyCell, OnceCell

Also consider whether you need a global at all. Passing a &Config or an Arc<State> into functions is easier to test and makes dependencies visible. Use globals for true process-wide singletons such as a logger or a compiled regex table.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a thread_local! value not need a lock?

    The macro creates a separate value per thread, lazily on first access. Because nothing is shared, no synchronization is needed and the type need not be Sync.
  2. 2. What happens if you call OnceLock::set on a cell that already holds a value?

    A OnceLock is written at most once. A second set hands your value back inside Err so you can see it was rejected.
  3. 3. Which type gives you a static whose value is built by a closure on first use?

    LazyLock::new(|| ...) stores the closure and runs it once, on the first dereference, from whichever thread gets there first.
  4. 4. You need a global list that many threads append to. What is the safe shape?

    A Mutex<Vec<T>> in a static allows safe mutation from any thread. OnceLock is write-once, static mut is a data race risk, and a thread-local is not shared at all.

Summary

  • A plain static must be Sync and immutable; static mut needs unsafe and is almost never the right answer.
  • thread_local! creates one lazily initialized value per thread; access it with with, or get/set/take/replace and with_borrow(_mut) on Cell and RefCell. Use const { } initializers when possible.
  • OnceLock is set once (set, get_or_init) and then read freely; LazyLock is a static that builds itself on first use.
  • For global state that changes, wrap a Mutex, RwLock or atomic in a static.
  • OnceCell and LazyCell are the unsynchronized versions for single-threaded use.
  • Prefer passing state explicitly when a true global is not needed.

Next: Async/await Basics