pub struct JoinSet<T> { /* private fields */ }
Expand description

A collection of tasks spawned on a Tokio runtime.

A JoinSet can be used to await the completion of some or all of the tasks in the set. The set is not ordered, and the tasks will be returned in the order they complete.

All of the tasks must have the same return type T.

When the JoinSet is dropped, all tasks in the JoinSet are immediately aborted.

Examples

Spawn multiple 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(async 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]);
    }
}

Implementations§

source§

impl<T> JoinSet<T>

source

pub fn new() -> JoinSet<T>

Create a new JoinSet.

source

pub fn len(&self) -> usize

Returns the number of tasks currently in the JoinSet.

source

pub fn is_empty(&self) -> bool

Returns whether the JoinSet is empty.

source§

impl<T> JoinSet<T>
where T: 'static,

source

pub fn spawn<F>(&mut self, task: F) -> AbortHandle
where F: Future<Output = T> + Send + 'static, T: Send,

Spawn the provided task on the JoinSet, returning an AbortHandle that can be used to remotely cancel the task.

The provided future will start running in the background immediately when this method is called, even if you don’t await anything on this JoinSet.

Panics

This method panics if called outside of a Tokio runtime.

source

pub fn spawn_on<F>(&mut self, task: F, handle: &Handle) -> AbortHandle
where F: Future<Output = T> + Send + 'static, T: Send,

Spawn the provided task on the provided runtime and store it in this JoinSet returning an AbortHandle that can be used to remotely cancel the task.

The provided future will start running in the background immediately when this method is called, even if you don’t await anything on this JoinSet.

source

pub fn spawn_local<F>(&mut self, task: F) -> AbortHandle
where F: Future<Output = T> + 'static,

Spawn the provided task on the current LocalSet and store it in this JoinSet, returning an AbortHandle that can be used to remotely cancel the task.

The provided future will start running in the background immediately when this method is called, even if you don’t await anything on this JoinSet.

Panics

This method panics if it is called outside of a LocalSet.

source

pub fn spawn_local_on<F>( &mut self, task: F, local_set: &LocalSet ) -> AbortHandle
where F: Future<Output = T> + 'static,

Spawn the provided task on the provided LocalSet and store it in this JoinSet, returning an AbortHandle that can be used to remotely cancel the task.

Unlike the spawn_local method, this method may be used to spawn local tasks on a LocalSet that is not currently running. The provided future will start running whenever the LocalSet is next started.

source

pub fn spawn_blocking<F>(&mut self, f: F) -> AbortHandle
where F: FnOnce() -> T + Send + 'static, T: Send,

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.

source

pub fn spawn_blocking_on<F>(&mut self, f: F, handle: &Handle) -> AbortHandle
where F: FnOnce() -> T + Send + 'static, T: Send,

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.

source

pub async fn join_next(&mut self) -> Option<Result<T, JoinError>>

Waits until one of the tasks in the set completes and returns its output.

Returns None if the set is empty.

Cancel Safety

This method is cancel safe. If join_next is used as the event in a tokio::select! statement and some other branch completes first, it is guaranteed that no tasks were removed from this JoinSet.

source

pub async fn shutdown(&mut self)

Aborts all tasks and waits for them to finish shutting down.

Calling this method is equivalent to calling abort_all and then calling join_next in a loop until it returns None.

This method ignores any panics in the tasks shutting down. When this call returns, the JoinSet will be empty.

source

pub fn abort_all(&mut self)

Aborts all tasks on this JoinSet.

This does not remove the tasks from the JoinSet. To wait for the tasks to complete cancellation, you should call join_next in a loop until the JoinSet is empty.

source

pub fn detach_all(&mut self)

Removes all tasks from this JoinSet without aborting them.

The tasks removed by this call will continue to run in the background even if the JoinSet is dropped.

source

pub fn poll_join_next( &mut self, cx: &mut Context<'_> ) -> Poll<Option<Result<T, JoinError>>>

Polls for one of the tasks in the set to complete.

If this returns Poll::Ready(Some(_)), then the task that completed is removed from the set.

When the method returns Poll::Pending, the Waker in the provided Context is scheduled to receive a wakeup when a task in the JoinSet completes. Note that on multiple calls to poll_join_next, only the Waker from the Context passed to the most recent call is scheduled to receive a wakeup.

Returns

This function returns:

  • Poll::Pending if the JoinSet is not empty but there is no task whose output is available right now.
  • Poll::Ready(Some(Ok(value))) if one of the tasks in this JoinSet has completed. The value is the return value of one of the tasks that completed.
  • Poll::Ready(Some(Err(err))) if one of the tasks in this JoinSet has panicked or been aborted. The err is the JoinError from the panicked/aborted task.
  • Poll::Ready(None) if the JoinSet is empty.

Note that this method may return Poll::Pending even if one of the tasks has completed. This can happen if the coop budget is reached.

Trait Implementations§

source§

impl<T> Debug for JoinSet<T>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl<T> Default for JoinSet<T>

source§

fn default() -> JoinSet<T>

Returns the “default value” for a type. Read more
source§

impl<T> Drop for JoinSet<T>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl<T> !RefUnwindSafe for JoinSet<T>

§

impl<T> Send for JoinSet<T>
where T: Send,

§

impl<T> Sync for JoinSet<T>
where T: Send,

§

impl<T> Unpin for JoinSet<T>

§

impl<T> !UnwindSafe for JoinSet<T>

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Any for T
where T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

§

fn type_name(&self) -> &'static str

§

impl<T> AnySync for T
where T: Any + Send + Sync,

§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync>

§

impl<T> ArchivePointee for T

§

type ArchivedMetadata = ()

The archived version of the pointer metadata for this type.
§

fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata

Converts some archived metadata to the pointer metadata for itself.
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<F, W, T, D> Deserialize<With<T, W>, D> for F
where W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized,

§

fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::Error>

Deserializes using the given deserializer
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> FutureExt for T

§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> Pointee for T

§

type Metadata = ()

The type for metadata in pointers and references to Self.
source§

impl<T> Same for T

§

type Output = T

Should always be Self
§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> Upcastable for T
where T: Any + Send + Sync + 'static,

§

fn upcast_any_ref(&self) -> &(dyn Any + 'static)

upcast ref
§

fn upcast_any_mut(&mut self) -> &mut (dyn Any + 'static)

upcast mut ref
§

fn upcast_any_box(self: Box<T>) -> Box<dyn Any>

upcast boxed dyn
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more