3 releases
0.1.2 | Jan 13, 2021 |
---|---|
0.1.1 | Jan 11, 2021 |
0.1.0 | Oct 23, 2020 |
#1413 in Rust patterns
Used in fb_stats
13KB
162 lines
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:
- define a counter/stat type. It needs to be Sync to satisfy PerThread/ThreadMap's constraints.
- set up a periodic thread/process to enumerate all the stats and accumulate them
- 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));
}