我想以线程安全的方式让多个线程访问相同的数据结构。
我可以做到这一点,它说我的RwLock
寿命不够长!我了解 Rust 的借贷,但这我无法理解。
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]
}
编译器说
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...
我似乎找不到任何这样做的例子。非常感谢任何想法或指示。