Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading