How to create a thread local variable inside of a Rust struct?
Asked Answered
M

2

8

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.

Maag answered 6/4, 2020 at 23:14 Comment(0)
M
10

Using a thread local variable in your struct can be done by placing it in an impl block:

use std::cell::RefCell;

struct Foo;
impl Foo {
    thread_local! {
        // Could add pub to make it public to whatever Foo already is public to.
        static FOO: RefCell<usize> = RefCell::new(0);
    }
}

And is accessible using Foo::FOO:

Foo::FOO.with(|x| println!("{:?}", x));

Playground
Note, however, that accessing this must be done using Foo:: preceding it, since it's not a field, but instead an associated static.

It could also be done by storing a reference to it:

use std::cell::RefCell;
use std::thread::LocalKey;

thread_local! {
    // Note lack of pub
    static FOO: RefCell<usize> = RefCell::new(0);
}
struct Bar {
    // Visibility here changes what can see `foo`.
    foo: &'static LocalKey<RefCell<usize>>,
    // Rest of your data.
}
impl Bar {
    fn constructor() -> Self {
        Self {
            foo: &FOO,
            // Rest of your data.
        }
    }
}
Mendacity answered 6/4, 2020 at 23:37 Comment(3)
Is it correct to say that this only works as long as there is one instance of the struct? Is there a way to allow multiple struct instances, or does that qualify as a separate question?Maag
This will work for any amount of struct instances. If you want only one struct instance, then your struct itself must go in a thread local variable. The first method will not depend on an instance of the struct existing though, the second one will.Mendacity
You can only access the static value with the closure in the with method. To get the value out of the with method, you have to clone the value. See for reference the comments in the code of thread_local!Halfwit
G
5

The easiest way is to use the thread_local crate:

struct Foo {
    thread_counter: ThreadLocal<AtomicU64>,
}

impl Foo {
    fn new() -> Foo {
        Foo {
            thread_counter: ThreadLocal::new(),
        }
    }
}
let foo = Foo::new();
let count = foo
    .thread_counter
    .get_or(|| AtomicU64::new(START_VALUE))
    .fetch_add(1, Ordering::Relaxed);
Gayl answered 22/7, 2020 at 16:13 Comment(1)
Unfortunately, this won't set a global value which is what I searched for and what I understood the OP wantsHalfwit

© 2022 - 2024 — McMap. All rights reserved.