Skip to content

Commit

Permalink
task: add JoinSet::spawn_blocking (#5612)
Browse files Browse the repository at this point in the history
  • Loading branch information
shepmaster committed Apr 17, 2023
1 parent 7aea597 commit f6cb6e0
Showing 1 changed file with 61 additions and 0 deletions.
61 changes: 61 additions & 0 deletions tokio/src/task/join_set.rs
Expand Up @@ -201,6 +201,67 @@ impl<T: 'static> JoinSet<T> {
self.insert(local_set.spawn_local(task))
}

/// Spawn the blocking code on the blocking threadpool and store
/// it in this `JoinSet`, returning an [`AbortHandle`] that can be
/// used to remotely cancel the task.
///
/// # Examples
///
/// Spawn multiple blocking tasks and wait for them.
///
/// ```
/// use tokio::task::JoinSet;
///
/// #[tokio::main]
/// async fn main() {
/// let mut set = JoinSet::new();
///
/// for i in 0..10 {
/// set.spawn_blocking(move || { i });
/// }
///
/// let mut seen = [false; 10];
/// while let Some(res) = set.join_next().await {
/// let idx = res.unwrap();
/// seen[idx] = true;
/// }
///
/// for i in 0..10 {
/// assert!(seen[i]);
/// }
/// }
/// ```
///
/// # Panics
///
/// This method panics if called outside of a Tokio runtime.
///
/// [`AbortHandle`]: crate::task::AbortHandle
#[track_caller]
pub fn spawn_blocking<F>(&mut self, f: F) -> AbortHandle
where
F: FnOnce() -> T,
F: Send + 'static,
T: Send,
{
self.insert(crate::runtime::spawn_blocking(f))
}

/// Spawn the blocking code on the blocking threadpool of the
/// provided runtime and store it in this `JoinSet`, returning an
/// [`AbortHandle`] that can be used to remotely cancel the task.
///
/// [`AbortHandle`]: crate::task::AbortHandle
#[track_caller]
pub fn spawn_blocking_on<F>(&mut self, f: F, handle: &Handle) -> AbortHandle
where
F: FnOnce() -> T,
F: Send + 'static,
T: Send,
{
self.insert(handle.spawn_blocking(f))
}

fn insert(&mut self, jh: JoinHandle<T>) -> AbortHandle {
let abort = jh.abort_handle();
let mut entry = self.inner.insert_idle(jh);
Expand Down

0 comments on commit f6cb6e0

Please sign in to comment.