多线程 – 在线程中使用方法时“类型不满足所需的生命周期”
发布时间:2020-12-15 04:30:34 所属栏目:Java 来源:网络整理
导读:我试图在Rust中的一个线程中使用一个方法,但我收到以下错误消息 :21:10: 21:23 error: the type [closure@anon:21:24: 23:14 tx:std::sync::mpsc::Senderi32,self:MyStruct,adder:i32,a:i32] does not fulfill the required lifetime :21 thread::spawn(move
我试图在Rust中的一个线程中使用一个方法,但我收到以下错误消息
这是示例代码: 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. 解决方法
问题是移动到线程的每个变量必须具有生命周期’静态.即线程不能引用不属于该线程的值.
在这种情况下,问题是self是对MyStruct实例的引用. 要解决此问题,请删除每个引用并克隆结构,然后再将其发送到线程. use std::thread; use std::sync::mpsc; #[derive(Clone)] struct MyStruct { field: i32 } impl MyStruct { fn my_fn(&self,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,rx.recv().unwrap()); } } fn main() { let ms = MyStruct{field: 42}; ms.threade_test(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |