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?
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.
I have written one for my crate lock-free: