I have a series of large structs I don't want to copy, and I want to apply a slow function to them . Since the slow function can be applied independently to each big struct, I want to do it concurrently.
All those big structs are in a container (a Vec
is a good representation of that). I can't spawn a thread for each element of the Vec
because borrowing one mutable element is the same as borrowing the whole vector each time.
struct SomeBigStruct {
pub variable: i32,
}
impl SomeBigStruct {
pub fn new() -> SomeBigStruct {
SomeBigStruct { variable: 0 }
}
}
fn some_slow_function(struct_in: &mut SomeBigStruct) {
println!("{}", struct_in.variable);
struct_in.variable += 1;
}
fn main() {
let mut vec_of_big_struct: Vec<SomeBigStruct> = Vec::new();
for i in 0..10 {
vec_of_big_struct.push(SomeBigStruct::new());
}
for struct_to_edit in vec_of_big_struct.iter_mut() {
some_slow_function(struct_to_edit);
} //Compiles but is slow
for struct_to_edit in vec_of_big_struct.iter_mut() {
std::thread::spawn(move || {
some_slow_function(struct_to_edit);
});
} //Can't compile because borrow checker isn't happy
}
Those aren't the actual struct or function, but the implementation details don't really matter.
What matters is that I don't want to copy the big struct because it is big, and I want to run the function concurrently on a mutable reference of that struct, knowing that each execution is independent.