Skip to main content

Module thread_local

Module thread_local 

Source
Expand description

RAII guard for thread-local caching of expensive-to-construct objects.

§Overview

When an object is expensive to construct but cheap to reset and must be used within a stateless function, keeping one instance per thread avoids repeated allocation. The manual take-then-return pattern is fragile: forgetting the return silently degrades to constructing a new instance.

Cached is an RAII guard whose Drop automatically returns the value to the thread-local slot, so forgetting the return is impossible.

§Synchronization

This cache provides no synchronization guarantees across threads. Each thread has an independent slot.

Within one thread, only one guard per cache can be held at a time. Attempting to acquire a second guard before dropping the first will panic.

§Examples

use commonware_utils::{thread_local_cache, Cached};

thread_local_cache!(static POOL: String);

let guard = Cached::take(&POOL, || Ok::<_, ()>(String::new()), |s| { s.clear(); Ok(()) }).unwrap();
assert_eq!(&*guard, "");
drop(guard);

// Second take reuses the cached instance.
let guard = Cached::take(&POOL, || Ok::<_, ()>(String::new()), |s| { s.clear(); Ok(()) }).unwrap();
drop(guard);

Structs§

Cached
RAII guard that borrows a value from a thread-local cache and returns it on drop.