Search code examples
rustmutex

Deep copies of Mutex<> in Rust?


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()
    }
    

    Having provided the literal answer, I still cannot shake off the feeling of xy problem. One might reasonably ask what's the point of mutexes that are not shared by anyone (since they were created for local use). More info might lead to a significantly better solution.