Crate perthread

source ·
Expand description

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)


use once_cell::sync::Lazy;
use perthread::{PerThread, ThreadMap};

// Set up the map of per-thread counters
static COUNTERS: Lazy<ThreadMap<usize>> = Lazy::new(ThreadMap::default);

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

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


  • 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.
  • 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.