Multithreading – when using a method in a thread, “the type does not meet the required lifecycle”
•
Java
I tried to use a method in a thread in rust, but I received the following error message
Here is the sample code:
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.
Solution
The problem is that each variable moved to a thread must have a lifetime 'static That is, a thread cannot reference a value that does not belong to the thread
In this case, the problem is that self is a reference to the mystruct instance
To fix this problem, delete each 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,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();
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
