Skip to content
CryoCryo home
Stdlibthread

local

import std::thread::local; · source

Types

ThreadLocal<T>

type struct ThreadLocal<T> {
    key: u32;

    init: () -> T;
    static new(init: () -> T) -> ThreadLocal<T>;
    get(&this) -> T*;
    clear(&this) -> void;
}

Each thread that touches a ThreadLocal<T> lazily gets its own heap-allocated T on first access; later accesses from the same thread return the same slot. Threads never see each other's values.

import std::thread::local;

mut buf: ThreadLocal<String> = ThreadLocal::<String>::new(() -> String { return String::new(); });
mut mine: String* = buf.get();

It is built on pthread_key_create with pthread_setspecific and pthread_getspecific; the per-thread value is heap-boxed and the void* TLS slot holds the box pointer. First access on a thread allocates and runs the init function pointer.

Cleanup is manual in v1. pthread_key_create accepts a destructor that runs at thread exit, and v1 passes null for it — so per-thread allocations are not freed automatically. Call clear() from each thread before it terminates, or accept the leak. For daemon-style threads that live as long as the process this is immaterial; short-lived workers should clear at exit. Wiring a per-T monomorphized destructor through the generic pipeline is what removes the limitation.

Properties

PropertyType
keyu32

Constructors

static new(init: () -> T) -> ThreadLocal<T>;

Construct a ThreadLocal<T> whose per-thread value is produced by calling init on first access from each thread. Panics on pthread key-creation failure (typically OOM in the kernel-side key table; rare).

Methods

init: () -> T;
get(&this) -> T*;

Get a raw pointer to the current thread's value, initializing it via init on first access. The pointer is stable for the lifetime of the thread (or until clear() is called by the same thread).

clear(&this) -> void;

Free the current thread's value if it has been initialized. Subsequent get() from this thread will re-run init. Other threads' values are untouched.

Trait implementations

implement<T> trait Drop for struct ThreadLocal<T>

Dropping the ThreadLocal deletes the key. It does not free other threads' slots — see the note above.