What is a good pattern for isolated multithreaded computation over a shared object?

Solution 1:

This is a good use for scoped threads (provided by crossbeam::scope or the higher-level utilities of rayon), which allow you to simply use an &Foo inside the threads. This avoids needing to move the value into and out of an Arc at all.

Also, if you use rayon you can greatly simplify your code by removing all of the explicit thread creation and joining in favor of its parallel iterators.

use rayon::iter::{ParallelIterator, IntoParallelIterator};

fn main() {
    let foo = Foo(0);
    let _res = process(&foo);
}

#[derive(Debug)]
struct Foo(u8);

fn process(foo: &Foo) -> u8 {
    (1..=5).into_par_iter().for_each(|_i: usize| {
        println!("{:?}", foo);
    });
    1
}