【问题标题】:Is there a way to poll several futures simultaniously in rust async有没有办法在 rust 异步中同时轮询多个期货
【发布时间】:2021-03-27 15:02:10
【问题描述】:

我正在尝试并行执行由迭代器给出的几个 sqlx 查询。 这可能是我目前为止最接近的。

let mut futures = HahshMap::new() // placeholder, filled HashMap in reality
    .iter()
    .map(async move |(_, item)| -> Result<(), sqlx::Error> {
        let result = sqlx::query_file_as!(
            // omitted
        )
            .fetch_one(&pool)
            .await?;
        channel.send(Enum::Event(result)).ignore();
        Ok(())
    })
    .clollect();
futures::future::join_all(futures);

所有查询和发送都是相互独立的,因此如果其中一个失败,其他的仍应得到处理。 此外,当前的异步关闭是不可能的。

【问题讨论】:

  • join_all() 有什么问题如果您想在任何完成后做某事,请使用select_all()
  • @HHK 地图不能这样工作。此外,我希望所有未来都能解决。

标签: asynchronous rust parallel-processing


【解决方案1】:

Rust 还没有 async 闭包。相反,您需要让闭包 return 成为一个异步块:

move |(_, item)| async move { ... }

此外,请确保 .await join_all 返回的未来,以确保实际轮询各个任务。

【讨论】:

  • 只是一些细微的变化:收集不起作用也没有必要。池或通道之类的东西需要克隆到异步块之外,否则它会抱怨cannot move out of 'channel', a captured variable in an 'FnMut' closure
猜你喜欢
  • 1970-01-01
  • 2022-01-25
  • 2020-10-10
  • 1970-01-01
  • 1970-01-01
  • 2013-09-29
  • 1970-01-01
  • 1970-01-01
  • 2021-01-25
相关资源
最近更新 更多