I have to generate a large Vec<Mutex<...>>
at the start of each iteration in my loop which gets mutated in the loop. Since regenerating it each iteration is quite expensive, I am looking for some way to initialize the vec only once, and make deep clones of the vector to use in the loop. Of course a simple .clone()
won’t work because the clone will still mutex-guard the same data in memory, not make copies of it. Something along the lines of
let my_vec = (0..big_usize).map(|_| Mutex::new(..)).collect();
for ... {
clone = my_vec.deep_clone();
mutate_clone_safely();
}
>Solution :
As pointed out by kmdreko in the comments, the deep_clone
you’re looking for could be implemented like this:
fn deep_clone<T: Clone>(v: &[Mutex<T>]) -> Vec<Mutex<T>> {
v.iter()
.map(|el| Mutex::new(el.lock().unwrap().clone()))
.collect()
}