gpt4 book ai didi

rust - 如何在调用线程方法时解决 “lifetime must be valid for the static lifetime”

转载 作者:行者123 更新时间:2023-12-03 11:42:05 25 4
gpt4 key购买 nike

我是Rust的初学者,无法编译以下代码。我知道这个问题可能并不新鲜,请尝试在各处搜索,但找不到以下问题的正确答案。

基本上,我试图从线程中调用方法,并且还使用不同的结构在线程之间发送和接收对象。

use std::{thread, time};

struct SenderStruct;

impl SenderStruct {
fn send(&self, sndr: Sender<(Option<String>)>) {
let count = 0;
loop {
sndr.send(Some(String::from("Hello"))).unwrap();
thread::sleep(time::Duration::from_millis(1000));
count = count + 1;

if count == 50 {
break;
}
}

sndr.send(None);
}
}

struct ReceiveStruct;

impl ReceiveStruct {
fn receive(&self, rec: Receiver<Option<String>>) {
loop {
let recv_out = rec.recv().unwrap();
match recv_out {
Some(some_str) => println!("{}", some_str),
None => break,
}
}
}
}

struct SendReceiveStruct {
m_ss: SenderStruct,
m_sos: ReceiveStruct,
m_recv_hndlr: Option<thread::JoinHandle<()>>,
}

impl SendReceiveStruct {
fn new() -> Self {
SendReceiveStruct {
m_ss: SenderStruct {},
m_sos: ReceiveStruct {},
m_recv_hndlr: None,
}
}

fn start(&mut self) {
let (tx, rx): (Sender<(Option<String>)>, Receiver<Option<String>>) = channel();

thread::spawn(move || self.m_ss.send(tx));
self.m_recv_hndlr = Some(thread::spawn(move || self.m_sos.receive(rx)));
}

fn wait_for_recevier(&mut self) {
self.m_recv_hndlr.unwrap().join();
}
}
fn main() {
println!("Hello, world!");

let mut ubs = SendReceiveStruct::new();
ubs.start();

ubs.wait_for_recevier();
}

但是我到处都遇到终身问题
$ cargo build
Compiling threads v0.1.0 (/root/learn-rust/threads)
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/main.rs:55:23
|
55 | thread::spawn(move || self.m_ss.send(tx));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 52:5...
--> src/main.rs:52:5
|
52 | / fn start(&mut self) {
53 | | let (tx, rx): (Sender<(Option<String>)>, Receiver<Option<String>>) = channel();
54 | |
55 | | thread::spawn(move || self.m_ss.send(tx));
56 | | self.m_recv_hndlr = Some(thread::spawn(move || self.m_sos.receive(rx)));
57 | | }
| |_____^
= note: ...so that the types are compatible:
expected &mut SendReceiveStruct
found &mut SendReceiveStruct
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the type `[closure@src/main.rs:55:23: 55:49 self:&mut SendReceiveStruct, tx:std::sync::mpsc::Sender<std::option::Option<std::string::String>>]` will meet its required lifetime bounds
--> src/main.rs:55:9
|
55 | thread::spawn(move || self.m_ss.send(tx));

任何指针(或其他引用)确实有帮助,还有其他解决上述问题的可能方法吗?

最佳答案

如果您检查 std::thread::spawn 的签名:

pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where
F: FnOnce() -> T,
F: Send + 'static,
T: Send + 'static,

及其文档紧密联系:

The 'static constraint means that the closure and its return value must have a lifetime of the whole program execution. The reason for this is that threads can detach and outlive the lifetime they have been created in.



但是, &mut self值闭包关闭的时间可能不够长。解决该问题的一种方法是克隆闭包实际使用的值:

#[derive(Clone)]
struct SenderStruct;

#[derive(Clone)]
struct ReceiveStruct;

impl SendReceiveStruct {
fn start(&mut self) {
let (tx, rx): (Sender<Option<String>>, Receiver<Option<String>>) = channel();

thread::spawn({
let ss = self.m_ss.clone();
move || ss.send(tx)
});
self.m_recv_hndlr = Some(thread::spawn({
let sos = self.m_sos.clone();
move || sos.receive(rx)
}));
}

fn wait_for_recevier(&mut self) {
self.m_recv_hndlr.take().unwrap().join();
}
}

除了其他几个小问题,您的代码现在可以编译。

关于rust - 如何在调用线程方法时解决 “lifetime must be valid for the static lifetime”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59544106/

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