Thread local member variables

Is there a way to create a thread local member variable? I saw a crate but it’s implementation was doing a hash table lookup every time. Usually C++ based APIs will do a 2 stage lookup but that implementation requires some sort of knowledge of when threads are destroyed to be bounded.

The only way to make thread locals is using thread_local! .

Note that the following code does work:

struct YourType { … }

impl YourType {
    thread_local! {
        static STATIC_MEMBER: … = …;
    }
}

// Or `Self::STATIC_MEMBER` if inside an
// `impl [Trait for] YourType` block
YourType::STATIC_MEMBER.with(|it| {
    …
})

The only limitation being that if YourType features generic parameters, then the thread_local! { static cannot depend on those (Rust does not support generic statics yet).


Note that this pattern is not as frequent in Rust since modules and visibility already serve the purpose of abstraction boundary that classes in other languages achieve.

https://crates.io/crates/thread_local

But it doesn't guarantee that it is bounded. (No hooks into thread destruction)

How about replacing it with

struct YourType {
    local: LocalType,
    shared: Arc<Mutex<SharedType>>
}

?

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.