local
import std::thread::local; · source
ThreadLocal<T>
type struct ThreadLocal<T> {
key: u32;
init: () -> T;
static new(init: () -> T) -> ThreadLocal<T>;
get(&this) -> T*;
clear(&this) -> void
where T: Drop;
}
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_createaccepts a destructor that runs at thread exit, and v1 passes null for it — so per-thread allocations are not freed automatically. Callclear()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-Tmonomorphized destructor through the generic pipeline is what removes the limitation.
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.