macro_rules! thread_local_rc {
() => { ... };
($(#[$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 Rc<T>.
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_rc() on the static variable to obtain a thread-specific linked instance
of the object, wrapped in an Rc. This does not limit you to a closure. Every .to_rc()
call returns an Rc 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_rc() and
reusing the returned Rc<T> for optimal performance.
If you are not making multiple calls or are not in a situation where you can store an Rc<T>,
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_rc!(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 Rc-style dynamic storage (i.e. not a single static variable) then consider
either passing instances of InstancePerThread<T> between threads or using
Family to manually control instance creation.