Skip to content

Commit

Permalink
去除有关 join_all 性能问题的推荐 (#10)
Browse files Browse the repository at this point in the history
Co-authored-by: Xidorn Quan <me@upsuper.org>
  • Loading branch information
bdbai and upsuper committed May 3, 2022
1 parent 20295bf commit 84e5f82
Showing 1 changed file with 1 addition and 4 deletions.
5 changes: 1 addition & 4 deletions content/await-multiple-futures.md
Expand Up @@ -6,9 +6,7 @@

如果想要在多个 `Future` 中的第一个完成后就返回,可以使用 futures 的 [`select`][select][`select_all`][select_all][`select_ok`][select_ok] 函数或 tokio 的 [`select!`][select-macro] 宏。

需要注意的是,上面这些函数和宏在每次被轮询的时候,都会轮询里面每一个未完成的 `Future`,因此当其所带的 `Future` 很多时可能会有性能问题。

使用 futures 提供的 [`FuturesOrdered`][FuturesOrdered][`FuturesUnordered`][FuturesUnordered] 这两个结构可以解决这一问题。它们是为管理大量的 `Future` 而设计的,只会去轮询收到了唤醒通知的 `Future`。它们将这些 `Future` 聚合成一个 [`Stream`][Stream] 逐个返回里面 `Future` 的结果,其中前者会按照输入的 `Future` 的顺序返回,而后者则是以任意顺序(可以近似看作按照完成顺序)返回。
此外,futures 还提供了 [`FuturesOrdered`][FuturesOrdered][`FuturesUnordered`][FuturesUnordered] 两个结构,它们将这些 `Future` 聚合成一个 [`Stream`][Stream] 逐个返回里面 `Future` 的结果。其中前者会按照输入的 `Future` 的顺序返回,而后者则是以任意顺序(可以近似看作按照完成顺序)返回。这两个结构额外提供了 `push` 方法来动态插入新的 `Future`,而且它们只会 `poll` 被唤醒的 `Future`,在 `Future` 数量较多时可能更高效。前面提到的 `join_all` 也会在一些情况下会自动使用 `FuturesOrdered` 来优化。


[futures]: https://crates.io/crates/futures
Expand All @@ -31,4 +29,3 @@
[join-macro]: https://docs.rs/tokio/1/tokio/macro.join.html
[try_join-macro]: https://docs.rs/tokio/1/tokio/macro.try_join.html
[select-macro]: https://docs.rs/tokio/1/tokio/macro.select.html

0 comments on commit 84e5f82

Please sign in to comment.