Skip to content

Commit a74dda3

Browse files
committed
Implement Extend for JoinSet
1 parent 0284d1b commit a74dda3

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

tokio/src/task/join_set.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -635,6 +635,47 @@ where
635635
}
636636
}
637637

638+
/// Extend a [`JoinSet`] with futures from an iterator.
639+
///
640+
/// This is equivalent to calling [`JoinSet::spawn`] on each element of the iterator.
641+
///
642+
/// # Examples
643+
///
644+
/// ```
645+
/// use tokio::task::JoinSet;
646+
///
647+
/// #[tokio::main]
648+
/// async fn main() {
649+
/// let mut set: JoinSet<_> = (0..5).map(|i| async move { i }).collect();
650+
///
651+
/// set.extend((5..10).map(|i| async move { i }));
652+
///
653+
/// let mut seen = [false; 10];
654+
/// while let Some(res) = set.join_next().await {
655+
/// let idx = res.unwrap();
656+
/// seen[idx] = true;
657+
/// }
658+
///
659+
/// for i in 0..10 {
660+
/// assert!(seen[i]);
661+
/// }
662+
/// }
663+
/// ```
664+
impl<T, F> std::iter::Extend<F> for JoinSet<T>
665+
where
666+
F: Future<Output = T>,
667+
F: Send + 'static,
668+
T: Send + 'static,
669+
{
670+
fn extend<I: IntoIterator<Item = F>>(&mut self, iter: I) {
671+
iter.into_iter().for_each(|task| {
672+
self.spawn(task);
673+
});
674+
}
675+
676+
}
677+
678+
638679
// === impl Builder ===
639680

640681
#[cfg(all(tokio_unstable, feature = "tracing"))]

0 commit comments

Comments
 (0)