Returning value from locked mutex

Hello, I am trying to access data elements guarded by an Arc<Mutex<Vec>>. The get function below is a causing the following compile error: 'cannot return value referencing local variable.' This makes sense however I am struggling to come up with the right solution. Any insights are appreciated..

use std::sync::{Arc, Mutex};

struct Data {
guarded_data: Arc<Mutex<Vec>>,
}

impl Data {
pub fn new() -> Data {
let v: Vec = vec!;
Data {
guarded_data: Arc::new(Mutex::new(v)),
}
}

fn add(&self, n: i32) {
    let mut d = self.guarded_data.lock().unwrap();
    d.push(n)
}

fn get(&self, index: usize) -> &i32 {
    let d = self.guarded_data.lock().unwrap();
    d.get(index).unwrap()
}

}

fn main() {
let data = Data::new();
data.add(1);
let n = data.get(0);
println!("Result: {}", n);
}

You can't keep a reference to the locked "thing" without holding the lock.

The simplest solution, in the case of i32 or similar types, is to return a copy (i32 instead of &i32) or clone. In other cases, where you don't want to clone the value, you can design the API so that it takes a closure operating on the locked &i32.

1 Like

Why is there a Mutex anyway? This should not need a Mutex to get working.

Another alternative is to use parking_lot and MutexGuard::map. But you'll have to return a &mut i32. playground

Thank you, well presented and helpful suggestions.

Good question; this is a simplified code snippet, the thinking was that I would use a similar data structure in a multi-threaded context.

Interesting, this is new to me, I will research and consider.

@new2rust If you can work with immutable values, then using a Mutex<Arc<Value>> will be a quick solution. Just clone the Arc and return the clone.
If that turns out to be too slow, or otherwise not practable, you will need to provide a lot more information as there are lots of possible solutions, all with different tradeoffs…

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.