Crate ref_thread_local[][src]

Expand description

A macro for declaring thread-local statics like using both of lazy_static! and RefCell

Using this macro, you can have thread-local statics be referenced by borrow() function like using a RefCell.

You may also initialize or destroy a static variable at any time you like.

Syntax

ref_thread_local! {
    [pub] static managed NAME_1: TYPE_1 = EXPR_1;
    [pub] static managed NAME_2: TYPE_2 = EXPR_2;
    ...
    [pub] static managed NAME_N: TYPE_N = EXPR_N;
}

Attributes (including doc comments) are supported as well:

ref_thread_local! {
    /// This is an example for using doc comment attributes
    static managed EXAMPLE: u8 = 42;
}

Semantics

For a given static managed NAME: TYPE = EXPR;, the macro generates a unique type that implements RefThreadLocal<T> trait and stores it in a static with name NAME. (Attributes end up attaching to this type.)

When calling any method of this unique type, it generated a RefManager<T> internally, which manage the reference count of borrowing, and initialize a internal thread-local static variable on calling initialize(), borrow(), borrow_mut(), borrow_mut(), try_borrow_mut() only if when uninitialized or destroyed.

Like RefCell, borrow() and borrow_mut() don’t return reference but instead Ref<'a, T> or RefMut<'a, T>, which manage a borrow count internally.

Like thread_local!, variables in ref_thread_local! will be dropped normally when thread is exiting or destroy() is called.

Example

Using the macro:

#[macro_use]
extern crate ref_thread_local;
use ref_thread_local::RefThreadLocal;

ref_thread_local! {
    static managed NUMBER: i32 = 233;
}

fn main() {
    let x = NUMBER.borrow(); // a Ref<'a, i32>
    println!("The number is {}.", x);
}

Additional Runtime Resource Usage Compared to thread_local!

In current version:

  • For each static variable in ref_thread_local!: 3 pointer variables, 1 Cell<isize>, 1 heap allocation.
  • For each reference: 1 reference
  • For each borrow: some borrow count operations, some function call (may be inlined)

Macros

Structs

Traits