Skip to content

Commit ebf3681

Browse files
committed
FuturesUnordered: Limit max value of yield_every
1 parent b48eb2e commit ebf3681

File tree

2 files changed

+8
-4
lines changed

2 files changed

+8
-4
lines changed

futures-util/src/stream/futures_unordered/mod.rs

+7-3
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use crate::task::AtomicWaker;
77
use alloc::sync::{Arc, Weak};
88
use core::cell::UnsafeCell;
9+
use core::cmp;
910
use core::fmt::{self, Debug};
1011
use core::iter::FromIterator;
1112
use core::marker::PhantomData;
@@ -393,11 +394,14 @@ impl<Fut: Future> Stream for FuturesUnordered<Fut> {
393394
// caps the number of calls to `poll` on underlying futures a single call to
394395
// `poll_next` is allowed to make.
395396
//
396-
// The value is the length of FuturesUnordered. This ensures that each
397-
// future is polled only once at most per iteration.
397+
// The value itself is chosen somewhat arbitrarily. It needs to be high enough
398+
// that amortize wakeup and scheduling costs, but low enough that we do not
399+
// starve other tasks for long.
400+
//
401+
// Each future is polled only once *at most* per iteration.
398402
//
399403
// See also https://github.com/rust-lang/futures-rs/issues/2047.
400-
let yield_every = self.len();
404+
let yield_every = cmp::min(self.len(), 32);
401405

402406
// Keep track of how many child futures we have polled,
403407
// in case we want to forcibly yield.

futures/tests/stream_futures_unordered.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -340,7 +340,7 @@ fn polled_only_once_at_most_per_iteration() {
340340

341341
let mut tasks = FuturesUnordered::from_iter(vec![F::default(); 33]);
342342
assert!(tasks.poll_next_unpin(cx).is_pending());
343-
assert_eq!(33, tasks.iter().filter(|f| f.polled).count());
343+
assert_eq!(32, tasks.iter().filter(|f| f.polled).count());
344344

345345
let mut tasks = FuturesUnordered::<F>::new();
346346
assert_eq!(Poll::Ready(None), tasks.poll_next_unpin(cx));

0 commit comments

Comments
 (0)