我如何从select_all取回期货?

问题描述

我需要下载很多文件,但是我想一次只处理3个文件。我正在从Tokio MPSC频道接收下一个文件URL。当我已经下载了2个文件并等待一个新文件时,我需要解决这种情况。

我如何等待3个期货中的一个并扩展前一个select_all

一个非常简化的示例:playground

use futures::{
    future::{select,select_all,Either},FutureExt,};
use tokio::time::{delay_for,Duration};

async fn exec(val: usize) {
    println!("Started {}",val);
    delay_for(Duration::from_millis(100)).await;
    println!("Executed {}",val);
}

async fn get_next() -> usize {
    use rand::Rng;
    delay_for(Duration::from_millis(100)).await;
    rand::thread_rng().gen_range(0,10)
}

#[tokio::main]
async fn main() {
    let mut tasks = Vec::new();
    for _ in 0..10 {
        if tasks.len() == 0 {
            let next = get_next().await;
            tasks.push(tokio::spawn(exec(next)));
            continue;
        }

        let all = select_all(tasks.drain(..));
        let next = get_next().boxed();

        match select(all,next).await {
            Either::Left(((_,_,left),_)) => tasks = left,Either::Right((a,_other)) => {
                // How can I get tasks futures from 'other'?
                // So on the next iteration,I'll be able to do select with an additional task.
                tasks.push(tokio::spawn(exec(a)));
            }
        };
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...