Threads question

I cannot pass a reference to a structure that does not have the Copy trait.

The structure is too big, I don't want to copy it.

The threads do not know that the main process will be around by the time they finish, so the structure may go out of scope.

Couldn't the invocation of a thread(s), have an option that says "The main thread is paused until the thread(s) is finished"?

Have you considered using Arc?

Note that if only one thread is accessing the struct, you can move the data to the thread, and get it back when you call join on the thread. If there's a lot of data, and would like to prevent copies you could do this with Box.

That can be accomplished with crossbeam's scope

1 Like

If you want a scopes thread pool, then use rayon::scope instead of crossbeam.

1 Like

I got this to work, Thanks!

// Get needs for all actions
pub fn get_needs(&mut self, cur: &SomeState, max_x: &SomeMask) -> NeedStore {
    // Run a get_needs thread for each action
    let mut vecx: Vec<NeedStore> = self
        .map(|actx| actx.get_needs(cur, max_x))
    // Aggregate the results into one NeedStore
    let mut nds_agg = NeedStore::new();
    for mut nst in vecx.iter_mut() {
        nds_agg.append(&mut nst);

Cool, it looks like you used rayon's amazing parallel iterators.
(I edited your post to format your code)

Hello Rusty,

Yes, and compiler wrestling.


I noticed that parallel processing can make a mess of multiple diagnostic print statements put in the code, as far as their order displayed on the screen. Simply replacing par_iter with iter, and par_iter_mut with iter_mut, can temporarily restore non-parallel processing.

Yes, this is intended behavior. If you run things in parallel, then their executions could interleave in unpredictable ways, which is why the outputs are messy.