I need a thread local variable, ideally stored in a struct which currently stores most of my program's global state.
The first way I can see to do this is to use the thread_local!
macro, however I would like to keep this thread local within my state struct.
The second way I can see to achieve this is to have a HashMap<Thread,MyThreadLocalData>
or similar between threads and the value of my thread local variable(s). I would then have a getter which uses thread::current
to lookup the appropriate value.
One last requirement which I should mention is that not all threads in the given program are created by Rust code, but Rust code may be run on any thread, so solutions should be robust to this.
Is there a best practice way of doing this? Perhaps there is a threadId
that would allow me to use a simple Vec
instead of a HashMap
(and/or avoid hashing overhead)? Is there a library for this?
Another option would be to modify the parameters of every function that could be used in a multithreaded context to take both a state struct and a threadlocal state struct, however this would not easily work with threads not created by Rust.