gpt4 book ai didi

multithreading - "the type does not fulfill the required lifetime"在线程中使用方法时

转载 作者:行者123 更新时间:2023-11-29 07:49:57 24 4
gpt4 key购买 nike

我试图在 Rust 的线程中使用方法,但我收到以下错误消息

: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();
}

Test it on the Rust Playground .

最佳答案

问题是每个移动到线程的变量都必须有生命周期'static。即线程不能引用不属于线程的值。

在这种情况下,问题是 self 是对 MyStruct 实例的引用。

要解决它,请删除所有引用并克隆结构,然后再将其发送到线程。

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();
}

关于multithreading - "the type does not fulfill the required lifetime"在线程中使用方法时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33442053/

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