我的目标是同时运行N个函数,但在所有函数完成之前不想再生成更多的函数。这是我到目前为止所拥有的:
每秒钟我生成5个函数,但现在我想等到所有的函数完成后再生成更多的函数。
据我理解(可能理解有误),我正在另一个 future 中返回一个
我被困在等待内部未来完成的过程中。
extern crate tokio;
extern crate futures;
use futures::future::lazy;
use std::{thread, time};
use tokio::prelude::*;
use tokio::timer::Interval;
fn main() {
let task = Interval::new(time::Instant::now(), time::Duration::new(1, 0))
.for_each(|interval| {
println!("Interval: {:?}", interval);
for i in 0..5 {
tokio::spawn(lazy(move || {
println!("Hello from task {}", i);
// mock delay (something blocking)
// thread::sleep(time::Duration::from_secs(3));
Command::new("sleep").arg("3").output().expect("failed to execute process");
Ok(())
}));
}
Ok(())
})
.map_err(|e| panic!("interval errored; err={:?}", e));
tokio::run(task);
}
每秒钟我生成5个函数,但现在我想等到所有的函数完成后再生成更多的函数。
据我理解(可能理解有误),我正在另一个 future 中返回一个
Future
。task (Interval ----------------------+ (outer future)
for i in 0..5 { |
tokio::spawn( ----+ |
// my function | (inner) |
Ok(()) | |
) ----+ |
} |
Ok(()) --------------------------+
我被困在等待内部未来完成的过程中。
tokio::spawn()
的用法。你的回答帮助我了解了如何“延迟”而不是使用thread::sleep
。但是,如果我想调用系统命令sleep N
,有没有一种方法可以“分组并等待”多个tokio::spawn()
的返回值,并在所有函数完成后继续执行下一批或者等待定义的时间间隔过去后再次调用所有函数? - nbariCommand::new("sleep").arg("3").output().expect("failed to execute process");
的方式进行模拟。 - nbaritokio::spawn
返回的值“实际上没有提供任何功能”(https://docs.rs/tokio/0.1.20/tokio/executor/struct.Spawn.html)。 - ShepmasterCommand
的链接(简而言之:使用tokio-process)。 - Shepmasterpage
的调用替换为对 tokio-threadpool 的调用,如链接的问答中所述。 - Shepmaster