thread_local_arc

Macro thread_local_arc 

Source
macro_rules! thread_local_arc {
    () => { ... };
    ($(#[$attr:meta])* $vis:vis static $NAME:ident: $t:ty = $e:expr; $($rest:tt)*) => { ... };
    ($(#[$attr:meta])* $vis:vis static $NAME:ident: $t:ty = $e:expr) => { ... };
}
Expand description

Declares that all static variables within the macro body contain thread-local linked objects.

A single instance from the same family is maintained per-thread, represented as an Arc<T>. This implies T: Send + Sync.

Call .with() to execute a closure with a shared reference to the current thread’s instance of the linked object. This is the most efficient way to use the static variable, although the closure style can sometimes be cumbersome.

Call .to_arc() on the static variable to obtain a thread-specific linked instance of the object, wrapped in an Arc. This does not limit you to a closure. Every .to_arc() call returns an Arc for the same instance per thread (though you may clone the T inside to create additional instances not governed by the mechanics of this macro).

§Accessing linked instances

If you are making multiple calls from the same thread, prefer calling .to_arc() and reusing the returned Arc<T> for optimal performance.

If you are not making multiple calls, you may yield optimal performance by calling .with() to execute a closure with a shared reference to the current thread’s linked instance.

§Example

linked::thread_local_arc!(static TOKEN_CACHE: TokenCache = TokenCache::with_capacity(1000));

fn do_something() {
    // `.with()` is the most efficient way to access the instance of the current thread.
    let token = TOKEN_CACHE.with(|cache| cache.get_token());
}

§Dynamic family relationships

If you need fully Arc-style dynamic storage (i.e. not a single static variable) then consider either passing instances of InstancePerThreadSync<T> between threads or using Family to manually control instance creation.

§Cross-thread usage

While you can pass the Arc returned by .to_arc() between threads, the object within will typically (depending on implementation choices) remain aligned to the original thread it was created on, which may lead to suboptimal performance if you try to use it on a different thread. For optimal multithreaded behavior, call .with() or .to_arc() on the thread the instance will be used on.