Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add spawn_blocking and spawn_blocking_on to the JoinSet builder #6578

Merged
merged 2 commits into from
May 22, 2024
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
47 changes: 46 additions & 1 deletion tokio/src/task/join_set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ impl<T: 'static> JoinSet<T> {

/// Tries to join one of the tasks in the set that has completed and return its output.
///
/// Returns `None` if the set is empty.
/// Returns `None` if the set is empty.
pub fn try_join_next(&mut self) -> Option<Result<T, JoinError>> {
// Loop over all notified `JoinHandle`s to find one that's ready, or until none are left.
loop {
Expand Down Expand Up @@ -623,6 +623,51 @@ impl<'a, T: 'static> Builder<'a, T> {
Ok(self.joinset.insert(self.builder.spawn_on(future, handle)?))
}

/// Spawn the blocking code on the blocking threadpool with this builder's
/// settings, and store it in the [`JoinSet`].
///
/// # Returns
///
/// An [`AbortHandle`] that can be used to remotely cancel the task.
///
/// # Panics
///
/// This method panics if called outside of a Tokio runtime.
///
/// [`JoinSet`]: crate::task::JoinSet
/// [`AbortHandle`]: crate::task::AbortHandle
#[track_caller]
pub fn spawn_blocking<F>(self, f: F) -> std::io::Result<AbortHandle>
where
F: FnOnce() -> T,
F: Send + 'static,
T: Send,
{
Ok(self.joinset.insert(self.builder.spawn_blocking(f)?))
}

/// Spawn the blocking code on the blocking threadpool of the provided
/// runtime handle with this builder's settings, and store it in the
/// [`JoinSet`].
///
/// # Returns
///
/// An [`AbortHandle`] that can be used to remotely cancel the task.
///
/// [`JoinSet`]: crate::task::JoinSet
/// [`AbortHandle`]: crate::task::AbortHandle
#[track_caller]
pub fn spawn_blocking_on<F>(self, f: F, handle: &Handle) -> std::io::Result<AbortHandle>
where
F: FnOnce() -> T,
F: Send + 'static,
T: Send,
{
Ok(self
.joinset
.insert(self.builder.spawn_blocking_on(f, handle)?))
}

/// Spawn the provided task on the current [`LocalSet`] with this builder's
/// settings, and store it in the [`JoinSet`].
///
Expand Down
Loading