我有一个异步方法,它应该并行执行一些futures,并且只有在所有futures完成后才返回。然而,它通过引用传递了一些数据,这些数据的生命周期不如'static
长(它会在主方法某个时刻被丢弃)。从概念上讲,它类似于这个(Playground):
async fn do_sth(with: &u64) {
delay_for(Duration::new(*with, 0)).await;
println!("{}", with);
}
async fn parallel_stuff(array: &[u64]) {
let mut tasks: Vec<JoinHandle<()>> = Vec::new();
for i in array {
let task = spawn(do_sth(i));
tasks.push(task);
}
for task in tasks {
task.await;
}
}
#[tokio::main]
async fn main() {
parallel_stuff(&[3, 1, 4, 2]);
}
现在,tokio希望传递给 spawn
的 futures 具有'static
生命周期的有效性,因为我可以在不停止 future 的情况下放弃句柄。这意味着我的上面的示例会产生此错误消息:
error[E0759]: `array` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
--> src/main.rs:12:25
|
12 | async fn parallel_stuff(array: &[u64]) {
| ^^^^^ ------ this data with an anonymous lifetime `'_`...
| |
| ...is captured here...
...
15 | let task = spawn(do_sth(i));
| ----- ...and is required to live as long as `'static` here
所以我的问题是:如何生成仅对当前上下文有效的未来,并等待它们全部完成?
async_scoped
- Ibraheem Ahmedspawn
的内容不需要具有'static
生命周期,它们只需要由'static
生命周期限定即可。这是一种常见的Rust生命周期误解。 - pretzelhammer