gpt4 book ai didi

rust - (tokio::spawn)借用的值生命周期不长-参数要求 `sleepy`是借用的 `' static`

转载 作者:行者123 更新时间:2023-12-03 11:37:06 27 4
gpt4 key购买 nike

此MWE显示tokio::spawn循环中for in的使用。注释的代码sleepy_futures.push(sleepy.sleep_n(2));可以正常工作,但不能运行/轮询异步功能。
基本上,我想同时运行一堆异步函数。我很高兴更改Sleepy的实现或使用其他库/技术。

pub struct Sleepy;
impl Sleepy {
pub async fn sleep_n(self: &Self, n: u64) -> String {
sleep(Duration::from_secs(n));
"test".to_string()
}
}

#[tokio::main(core_threads = 4)]
async fn main() {
let sleepy = Sleepy{};

let mut sleepy_futures = vec::Vec::new();
for _ in 0..5 {
// sleepy_futures.push(sleepy.sleep_n(2));
sleepy_futures.push(tokio::task::spawn(sleepy.sleep_n(2)));
}

let results = futures::future::join_all(sleepy_futures).await;
for result in results {
println!("{}", result.unwrap())
}
}

最佳答案

这是修复问题的粗略方法:

use tokio::time::delay_for;

pub struct Sleepy;
impl Sleepy {
pub async fn sleep_n(n: u64) -> String {
delay_for(Duration::from_secs(n)).await;
"test".to_string()
}
}
现在,它不再 anchor 定到任何特定的Sleepy实例,从而消除了生命周期问题。您会像 Sleepy::sleep_n这样称呼它。
如果需要 &self,则需要做更多的工作:
use std::sync::Arc;
use std::time::Duration;
use std::vec;
use tokio;
use tokio::time::delay_for;

pub struct Sleepy;
impl Sleepy {
pub async fn sleep_n(&self, n: u64) -> String {
// Call .await here to delay properly
delay_for(Duration::from_secs(n)).await;
"test".to_string()
}
}

#[tokio::main(core_threads = 4)]
async fn main() {
env_logger::init();

let sleepy = Arc::new(Sleepy {});

let mut sleepy_futures = vec::Vec::new();
for _ in 0..5 {
let sleepy = sleepy.clone();

// Dictate that values are moved into the task instead of
// being borrowed and dropped.
sleepy_futures.push(tokio::task::spawn(async move {
sleepy.sleep_n(2).await
}));
}

let results = futures::future::join_all(sleepy_futures).await;
for result in results {
println!("{}", result.unwrap())
}
}
此处 Arc用于包装对象,因为 task可能使用线程,因此 Rc不够。

关于rust - (tokio::spawn)借用的值生命周期不长-参数要求 `sleepy`是借用的 `' static`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63347498/

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