“类型不能满足要求的寿命".在线程中使用方法时 [英] "the type does not fulfill the required lifetime" when using a method in a thread
问题描述
我正在尝试在Rust的线程中使用方法,但收到以下错误消息
I am trying to use a method in a thread in Rust, but I get the following error message
:21:10:21:23错误:类型
[closure@<anon>:21:24: 23:14 tx:std::sync::mpsc::Sender<i32>, self:&MyStruct, adder:i32, a:i32]
无法满足要求的寿命:21
thread :: spawn(move || { ^ ~~~~~~~~~~~~~:18:9:24:10注意:在此for循环扩展中注意:类型必须超过静态 终身错误:由于先前的错误而中止
:21:10: 21:23 error: the type
[closure@<anon>:21:24: 23:14 tx:std::sync::mpsc::Sender<i32>, self:&MyStruct, adder:i32, a:i32]
does not fulfill the required lifetime :21
thread::spawn(move || { ^~~~~~~~~~~~~ :18:9: 24:10 note: in this expansion of for loop expansion note: type must outlive the static lifetime error: aborting due to previous error
这是示例代码:
use std::thread;
use std::sync::mpsc;
struct MyStruct {
field: i32
}
impl MyStruct {
fn my_fn(&self, adder1: i32, adder2: i32) -> i32 {
self.field + adder1 + adder2
}
fn threade_test(&self) {
let (tx, rx) = mpsc::channel();
let adder = 1;
let lst_adder = vec!(2, 2, 2);
for a in lst_adder {
let tx = tx.clone();
thread::spawn(move || {
let _ = tx.send(self.my_fn(adder, a));
});
}
println!("{}", rx.recv().unwrap());
}
}
fn main() {
let ms = MyStruct{field: 42};
ms.threade_test();
}
推荐答案
问题在于,每个移至线程的变量都必须具有生存期'static
.即线程不能引用该线程不拥有的值.
The problem is that every variable moved to the thread must have the lifetime 'static
. i.e. threads can't reference values which are not owned by the thread.
在这种情况下,问题是self
是对MyStruct
实例的引用.
In this case the problem is that self
is a reference to an instance of MyStruct
.
要解决此问题,请删除所有引用并克隆结构,然后再将其发送给线程.
To solve it, remove every reference and clone the structure before sending it to the thread.
use std::thread;
use std::sync::mpsc;
#[derive(Clone)]
struct MyStruct {
field: i32
}
impl MyStruct {
fn my_fn(&self, adder1: i32, adder2: i32) -> i32 {
self.field + adder1 + adder2
}
fn threade_test(&self) {
let (tx, rx) = mpsc::channel();
let adder = 1;
let lst_adder = vec!(2, 2, 2);
for a in lst_adder {
let tx = tx.clone();
let self_clone = self.clone();
thread::spawn(move || {
let _ = tx.send(self_clone.my_fn(adder, a));
});
}
println!("{}", rx.recv().unwrap());
}
}
fn main() {
let ms = MyStruct{field: 42};
ms.threade_test();
}
这篇关于“类型不能满足要求的寿命".在线程中使用方法时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!