gpt4 book ai didi

multithreading - rust : borrowed value does not live long enough 中的生命周期问题

转载 作者:行者123 更新时间:2023-11-29 08:28:39 44 4
gpt4 key购买 nike

我在下面的简短代码中重现了我的问题。

问题:内部线程 使用来自外部线程 的变量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's scope :

let v = vec![0, 1];
let test = Test { v: &v }; //inner_thread
crossbeam::thread::scope(|scope| {
scope.spawn(|_| test.print());
}).unwrap();

关于multithreading - rust : borrowed value does not live long enough 中的生命周期问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57214992/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com