Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Traversing ThreadLocal did not retrieve the contents of all thread local variables #78

Closed
anonymousGiga opened this issue Jun 18, 2024 · 4 comments

Comments

@anonymousGiga
Copy link

I run the following code:

use std::cell::Cell;
use std::sync::Arc;
use std::thread;
use thread_local::ThreadLocal;

fn main() {
    let tls = Arc::new(ThreadLocal::new());

    for _ in 0..5 {
        let tls2 = tls.clone();
        thread::spawn(move || {
            let cell = tls2.get_or(|| Cell::new(0));
            cell.set(1);
        })
        .join()
        .unwrap();
    }

    let tls = Arc::try_unwrap(tls).unwrap();
    let mut all_prams = vec![];
    tls.into_iter().for_each(|y| all_prams.push(y.get()));
    assert_eq!(all_prams, vec![1, 1, 1, 1, 1]);
}

Report the follow error:

all_prams: [1]
thread 'main' panicked at src/main.rs:21:5:
assertion `left == right` failed
  left: [1]
 right: [1, 1, 1, 1, 1]
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Isn't the threadlocal object reporting an error with the content in each thread? Why is this happening?

@Amanieu
Copy link
Owner

Amanieu commented Jun 19, 2024

This is working as intended: if a thread has exited then we can re-use its thread-local copy for another thread.

@anonymousGiga
Copy link
Author

This is working as intended: if a thread has exited then we can re-use its thread-local copy for another thread.

I hope each thread saves a copy. Is there any way to implement this?

@Amanieu
Copy link
Owner

Amanieu commented Jun 21, 2024

You can use a HashMap<ThreadId, T> in each thread-local variable and then merge the maps at the end. This will still be faster than using a Mutex<HashMap>.

@anonymousGiga
Copy link
Author

You can use a HashMap<ThreadId, T> in each thread-local variable and then merge the maps at the end. This will still be faster than using a Mutex<HashMap>.

Ok,Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants