task
Tasks are cooperative: they run on the calling thread and switch only at
suspension points (IO waits, sleep, join, recv, yield_now). Every task
lives inside a scope, which does not return until all of its children have
finished, so no task outlives the code that started it.
Use tasks for concurrent IO; use threads for CPU-bound work. The tasks tutorial walks through the model.
Written in Coil and shipped inside the compiler.
Import what you use (use path::* is not allowed):
use task::{TaskError, Scope};
Types#
| Name | Description |
|---|---|
TaskError | Why a task or a scope did not produce its value. |
Scope | A running scope, used to start child tasks with spawn. |
Task | A handle to a child task started with Scope::spawn. |
ChannelError | Why a channel operation failed. |
Channel | A bounded queue for passing values between tasks. |
Functions#
| Name | Description |
|---|---|
scope | Runs body with a Scope for starting child tasks, and returns its value once body and every child have finished. |
sleep | Suspends the current task for at least ms milliseconds; other tasks run meanwhile. |
yield_now | Lets other ready tasks run before the current one continues. |
timeout | Runs body as a task and cancels it if it has not finished after ms milliseconds. |
shield | Runs body so that a cancel waits for it to finish instead of interrupting it. |
channel | Creates a channel that holds up to capacity values. |
blocking | Runs work on another OS thread and waits for its result; only the current task waits, the others keep running. |
blocking_with | Like blocking, passing arg to work (it is copied to the other thread, like thread::spawn(work, arg)). |
block_on | Resumes the coroutine handle until it is done and returns its completion value; values it yields are discarded. |