1

我想运行一个有很多不同变量的函数

假设我的功能是:

async fn do_the_hard_job(my_input: u16) {
    ...
    // do the hard job that takes some time
    if my_condition {
        println!("{}", input);
    }
}

我想为许多输入运行这个函数;假设我的输入是

inputs = stream::iter(1..=u16::MAX);

由于该函数花费了一些周期,我希望尽可能同时运行所有输入。所以我可以像这样运行

 inputs.for_each_concurrent(0, |input| do_the_hard_job(input))
       .await;

到目前为止,一切都很好; 我用这个函数运行了所有的输入并得到我的输出stdout。但是,如果我希望将输出写入某个输出文件怎么办?

我无法打开文件并在do_the_hard_job函数中附加到它。那会搞砸的。我无法将文件添加为参数,因为该方法将同时运行,哪个将借用可变文件。

我尝试返回值而不是在方法中打印,然后收集返回的值;像这样 :

let mut return_values:Vec<u16> = Vec::new();
inputs
    .for_each_concurrent(0, |input| async move {
        if let done = do_the_hard_job(port).await{
            if done > 0 {
                return_values.push(port);
            }
        }}).await;

可悲的是,这没有奏效。我可以尝试什么来实现我的目标?

编辑:我为这个问题准备了一个复制器:https ://github.com/kursatkobya/bite-sized-qualms/tree/main/concurrent-write

4

1 回答 1

1

您可以组合thencollect获得结果:

use futures::{stream, StreamExt};
use std::{
    time::Duration,
};

#[tokio::main]
async fn main() {
    let inputs = stream::iter(0..=10);

    // Finaly the one below does not work
    let output_values: Vec<u16> = inputs
        .then(|input: u16| async move {
            let result = f(input).await;
            result
        }).collect::<Vec<u16>>().await;
    println!("{:?}", output_values);

}

async fn f(input: u16) -> u16 {
    tokio::time::sleep(Duration::from_millis(200)).await;
    input
}

操场

于 2021-10-26T16:09:10.523 回答