fn calc(x: Vec<i32>, y: i32) -> Vec<i32> {
//some block take long time to calculate
x.iter().map(|x| x + y).collect()
}
let a = vec![1i32, 2, 3];//some very large vector
let res1 = spawn(move || calc(a.clone(), 1))
let res2 = spawn(move || calc(a.clone(), 2))
let res3 = spawn(move || calc(a.clone(), 3))
So, every time I start a spawn I have to clone a. a is a very large Vec, cloning it is expensive.
Is there a way I can use spawn withing using refrence? Like this:
fn calc(x: &Vec<i32>, y: i32) -> Vec<i32> {
//some block take long time to calculate
x.iter().map(|x| x + y).collect()
}
let a = vec![1i32, 2, 3];//some very large vector
let res1 = spawn(|| calc(&a, 1))
let res2 = spawn(|| calc(&a, 2))
let res3 = spawn(|| calc(&a, 3))
Your function is defined to take ownership of the Vec so you will always need to clone to call it multiple times for the same Vec. You don't appear to need ownership though, so you can change calc to take a reference[1]
You can use std::thread::scope on recent rust versions to spawn threads that can borrow from the current thread. The catch is that the threads are all joined[2] before the call to scope returns, which may not be what you want[3].
You can also imitate scope with an Arc if you're on an older version of rust[4]