Per-thread per-object storage? (thread-local, but not static)

I’m looking for a crate or design pattern for using thread-local storage, but in a way that stores separate values per object per thread.

thread_local! is for static variables, and I’m looking for thread-local equivalent of a regular property/object property.

I imagine it’d be something like a HashMap with thread ID as the key. Does this exist already?

1 Like

https://crates.io/crates/thread_local (haven’t used it personally though)

2 Likes

In addition to the thread_local crate linked above, there’s also https://crates.io/crates/thread-local-object. They differ in the tradeoffs of their implementations: with thread_local, the thread-local values associated with an object are freed when the object is, and with thread-local-object the values associated with a thread are freed when the thread dies.

thread-local is then better for relatively short lived values, and thread-local-object is better for long-lived values which will be shared by many threads.

2 Likes

I have written one for my crate lock-free:

https://docs.rs/lockfree/0.5.1/lockfree/tls/struct.ThreadLocal.html