# Macro std::thread_local

1.0.0 · source ·

    macro_rules! thread_local {
        () => { ... };
        ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = const { $init:expr }; $($rest:tt)*) => { ... };
        ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = const { $init:expr }) => { ... };
        ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => { ... };
        ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr) => { ... };
    }

Expand description

Declare a new thread local storage key of type `std::thread::LocalKey`.

## Syntax

The macro wraps any number of static declarations and makes them thread local. Publicity and attributes for each static are allowed. Example:

    use std::cell::RefCell;
    thread_local! {
        pub static FOO: RefCell<u32> = RefCell::new(1);

        static BAR: RefCell<f32> = RefCell::new(1.0);
    }

    FOO.with(|foo| assert_eq!(*foo.borrow(), 1));
    BAR.with(|bar| assert_eq!(*bar.borrow(), 1.0));

Run

This macro supports a special `const {}` syntax that can be used when the initialization expression can be evaluated as a constant. This can enable a more efficient thread local implementation that can avoid lazy initialization. For types that do not need to be dropped, this can enable an even more efficient implementation that does not need to track any additional state.

    use std::cell::Cell;
    thread_local! {
        pub static FOO: Cell<u32> = const { Cell::new(1) };
    }

    FOO.with(|foo| assert_eq!(foo.get(), 1));

Run

See `LocalKey` documentation for more information.