Concurrent Access to a Vector

I have a problem to solve as following: I need to implement function that takes index and closure. It searches for the value for the given index and if it finds, it should return the value. Otherwise, it should compute the closure and store it at the end. I implemented as below:

Struct A { value: Mutex<Vec<V>>, } 
impl A { 
pub fn get_concurrency<V: Clone>(&idx: usize, self, f: F: FnOnce() -> V) -> V 
{ 
let vec = self.lock().unwrap(); 
if (*vec).get(idx).is_none { 
drop(vec);
let v = f();
 let vec = self.lock().unwrap(); 
vec.push(v.clone()); 
v 
} else {
 (*vec).get(idx).unwrap() 
} } }

I drop after I learn that it does not contain the value and do the computation. If I do not do so, when I run function f in multiple threads, I can end up in deadlock. With the current implementation the problem is that when it runs concurrently, it executes input closure f for the same index several times, which is a bug. Anyone could help me with it?

In that case you will end up in a deadlock only if f calls get_concurrency, if you avoid that you're fine.

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.