Release data from Mutex

I have the following code:

fn foo(sutff: Vec<Stuff?) -> Vec<Thing> {
    let things = Mutex::new(Vec::new::<Thing>());
    stuff.par_iter().for_each(|stuff| {
        let thing = stuff.to_thing();
        let things = things.lock().unwrap();
    // How do I return the Vec<Thing>?

Dereferencing the lock guard does not help.
I am currently doing the following:

let mut things = things.lock().unwrap();
let mut out_things = Vec::new();
out_things.append(&mut things);
return out_things;

Is there a better way to do this?

If you no longer need the mutex, you can use into_inner to get the stored value back.

1 Like


If .push() is the only thing you do with the mutexed vector, you can .collect() the parallel iterator without mutex to get results in order.


Well, I had come here for help on one thing and I got help on another thing as well.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.