2 releases

0.1.2 Mar 11, 2024
0.1.1 Nov 15, 2023
0.1.0 Nov 13, 2023

#965 in Rust patterns

Download history 2/week @ 2024-02-15 13/week @ 2024-02-22 7/week @ 2024-02-29 141/week @ 2024-03-07 49/week @ 2024-03-14 34/week @ 2024-03-28 18/week @ 2024-04-04

52 downloads per month

MIT license

19KB
415 lines

lazy_thread_local

Docs Crates.io Crates.io

Lazy Per-object thread-local storage

This library provides the ThreadLocal type which allows a separate copy of an object to be used for each thread. This allows for per-object thread-local storage, unlike the crate thread_local, this crate provides lazy initialisation and does not depend on std.

Per-thread objects are not destroyed when a thread exits. Instead, objects are only destroyed when the ThreadLocal containing them is dropped.

This crate uses platform dependent methods to create thread local keys. On Unix, pthread local storage is used. On windows, Fibers storage is used. On wasm, it relies on std to provide thread id.

Examples

Basic usage of ThreadLocal:

use lazy_thread_local::ThreadLocal;
let mut tls: ThreadLocal<u32> = ThreadLocal::new(||5);
assert_eq!(tls.get(), &5);
*tls = 6;
assert_eq!(tls.get(), &6);

Initialising ThreadLocal in constant context:

use lazy_thread_local::ThreadLocal;

static TLS: ThreadLocal<u32> = ThreadLocal::const_new(5);

assert_eq!(TLS.get(), 5);

Dependencies

~185KB