Skip to content
This repository was archived by the owner on Nov 23, 2024. It is now read-only.

去除有关 join_all 性能问题的推荐 #10

Merged
merged 2 commits into from
May 3, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions content/await-multiple-futures.md
Original file line number Diff line number Diff line change
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