What are Tasks?
A task is a light weight, non-blocking unit of execution. Tasks are similar to OS threads but are managed by the Tokio runtime instead of the OS scheduler. They are sometimes called green threads, similar to Go’s goroutines, Kotlin’s coroutines, or Erlang’s processes.Key Characteristics
Light Weight
Creating, running, and destroying tasks has very low overhead compared to OS threads.
Cooperative
Tasks use cooperative multitasking, yielding control at
.await points rather than being preempted.Non-Blocking
Tasks must not perform blocking operations that would prevent other tasks from executing.
Spawning Tasks
spawn
Spawns a new asynchronous task, returning a
JoinHandle for it.Type Constraints:F: Future + Send + 'staticF::Output: Send + 'static
future: The async block or future to execute
JoinHandle<F::Output> - A handle to await the task’s resultExample:The provided future will start running in the background immediately when
spawn is called, even if you don’t await the returned JoinHandle.Spawning Multiple Tasks
JoinHandle
AJoinHandle is returned by spawn and represents the spawned task. It can be awaited to get the task’s result.
Methods
Waits for the task to complete and returns its result.Returns:
Ok(T): Task completed successfully with output TErr(JoinError): Task panicked or was cancelled
Aborts the task. The task will be cancelled at the next
.await point.Example:Checks if the task has completed. Returns
true if the task has finished, false otherwise.Example:Cancellation
Tasks can be cancelled using theabort() method on their JoinHandle or AbortHandle.
AbortHandle
A handle that can abort a task. Unlike
JoinHandle, it cannot await the result, but multiple AbortHandles can exist for a single task.Example:Blocking Operations
spawn_blocking
Spawns a blocking function on a dedicated thread pool.Type Constraints:
F: FnOnce() -> R + Send + 'staticR: Send + 'static
f: The blocking function to execute
JoinHandle<R> - A handle to await the resultExample:Use
spawn_blocking for CPU-intensive work or calling synchronous APIs that would block. This prevents blocking the async runtime threads.block_in_place
Runs a blocking function by converting the current worker thread to a blocking thread.Only available with the multi-threaded runtime.Type Constraints:
F: FnOnce() -> R
f: The blocking function to execute
R - The result of the functionExample:Yielding
yield_now
Yields execution back to the Tokio runtime, allowing other tasks to run.Example:
Local Tasks
LocalSet
A set of tasks that are executed on the same thread. Allows spawning
!Send futures.Example:spawn_local
Spawns a
!Send future onto the current LocalSet.Type Constraints:F: Future + 'static(note: NOT required to beSend)
JoinSet
A collection of tasks that allows joining multiple tasks efficiently.Example:
JoinSet Methods
Spawns a task onto the
JoinSet.Returns: An AbortHandle that can be used to cancel the taskWaits for the next task to complete. Returns
None when all tasks have completed.Aborts all tasks in the set.
Task IDs
Returns the ID of the currently running task.Panics: If called from outside a taskExample:
Returns the ID of the currently running task, or
None if called outside a task.Best Practices
Spawn tasks liberally
Tasks are cheap. Don’t hesitate to spawn many tasks for concurrent operations.
Use spawn_blocking for blocking code
Never block the async runtime threads. Use
spawn_blocking for synchronous APIs.