[][src]Crate perthread

Provides ThreadMap structure for accessing PerThread thread local variables from a static context via ThreadMap::for_each.

Notes: If we wanted to do a global accumulator for the per-thread stats we'd need to:

  1. define a counter/stat type. It needs to be Sync to satisfy PerThread/ThreadMap's constraints.
  2. set up a periodic thread/process to enumerate all the stats and accumulate them
  3. give the stat type a Drop implementation which also updates the accumulator, so that stats are recorded when the thread dies (otherwise it loses stats after the last accumulator pass, and short-lived threads may never record stats at all)

Examples:

use lazy_static::lazy_static;
use perthread::{PerThread, ThreadMap};

// Set up the map of per-thread counters
lazy_static! {
    static ref COUNTERS: ThreadMap<usize> = ThreadMap::default();
}

// Declare a specific per-thread counter
thread_local! {
    static COUNTER: PerThread<usize> = COUNTERS.register(0);
}

fn main() {
    COUNTER.with(|c| println!("COUNTER: {:?}", *c));
}

Structs

PerThread

Values inserted into the map are returned to the caller inside this wrapper. The caller will hold on to this wrapper as long as they like, then when they drop it the corresponding entry is removed from the map.

ThreadMap

This is a structure that lets you define a map with thread local variables, but also gives you access to all them behind a Mutex.