我在下面的短代码中重现了我的问题。
问题:inner thread
使用来自outer thread
的变量v
的引用。rust 编译器抛出错误,因为"技术上"outer thread
可能会在inner thread
之前终止,因此inner thread
可能会失去对变量v
的访问。但是在下面的代码中,这显然不会发生。
问:我应如何更改此代码以使其符合要求,同时保持相同的功能?
fn main() { //outer thread
let v = vec![0, 1];
let test = Test { v: &v }; //inner_thread
std::thread::spawn(move || test.print());
loop {
// this thread will never die because it will never leave this loop
}
}
pub struct Test<'a> {
v: &'a Vec<u32>,
}
impl<'a> Test<'a> {
fn print(&self) {
println!("{:?}", self.v);
}
}
error[E0597]: `v` does not live long enough
--> src/main.rs:3:26
|
3 | let test = Test { v: &v }; //inner_thread
| ^^ borrowed value does not live long enough
4 | std::thread::spawn(move || test.print());
| ---------------------------------------- argument requires that `v` is borrowed for `'static`
...
8 | }
| - `v` dropped here while still borrowed
显而易见的解决方案是让 Test 拥有向量,而不仅仅是有一个引用。
但是如果你真的需要借用线程中的值(可能是因为你想在执行结束后使用它(,那么你可以使用 crossbeam 的作用域:
let v = vec![0, 1];
let test = Test { v: &v }; //inner_thread
crossbeam::thread::scope(|scope| {
scope.spawn(|_| test.print());
}).unwrap();