I want to have give multiple threads access to the same data structure in a thread-safe manner.
I can get as far as this, where it says that my RwLock
does not live long enough! I understand the lending and borrowing of Rust, but this I can't wrap my head around.
use std::sync::RwLock;
use std::thread;
fn func<'a>(vec_lock: &'a RwLock<Vec<i32>>) {
let mut vec = vec_lock.write().unwrap();
vec.push(2);
}
fn main() {
let v: Vec<i32> = Vec::new(); // Shared data
let v_lock = &RwLock::new(v); // RwLock ref
let t1 = thread::spawn(move || func(v_lock)); // Give lock ref to func
let t2 = thread::spawn(move || func(v_lock)); // Give lock ref to func
t1.join().unwrap(); // Wait
t2.join().unwrap();
// Here v should be [2,2]
}
The compiler says
error[E0597]: borrowed value does not live long enough
--> src/main.rs:11:19
|
11 | let v_lock = &RwLock::new(v);
| ^^^^^^^^^^^^^^ temporary value does not live long enough
...
19 | }
| - temporary value only lives until here
|
= note: borrowed value must be valid for the static lifetime...
I cannot seem to find any examples that do this. Any ideas or pointers are greatly appreciated.