Skip to content

Q061. What is the relationship between a future, a task, and an executor?

Short Answer

A future is the computation's state and polling logic. A task is an independently scheduled future plus runtime metadata such as readiness, a waker, and cancellation or join state. An executor owns ready queues and polls runnable tasks. A runtime such as Tokio combines an executor with facilities such as timers, I/O drivers, and blocking-work support.

Deep Dive

Awaiting a future nests it inside the current task: the parent task polls the child as part of its own state machine. Spawning wraps a future in a new task, allowing it to be scheduled independently and returning a handle for its result.

The executor does not normally poll every task continuously. When a task's future returns Pending, the executor stops polling it until its waker marks it ready again. This separation lets futures remain runtime-agnostic at the trait level.

The terms are often blurred in conversation, but distinguishing them prevents errors such as saying a future is already running or that .await creates a task.

Internal Model

A task allocation commonly contains the future, scheduling state, reference counts, output storage, and a waker representation. The executor pushes ready tasks onto local or global queues and invokes poll with a Context.

When a task completes, its output is made available to its join mechanism and the task no longer returns to the ready queue.

Example

rust
async fn compute() -> u64 {
    40 + 2
}

#[tokio::main]
async fn main() {
    let future = compute();
    let task = tokio::spawn(future);

    assert_eq!(task.await.unwrap(), 42);
}

Common Mistakes

  • Using future, task, executor, and runtime as interchangeable terms.
  • Saying .await always creates a separately scheduled task.
  • Assuming the standard library supplies one mandatory global executor.

Follow-ups

  • What metadata must a task store beyond its future?
  • How does a waker reconnect an event source to the correct task?
  • What changes when a future is spawned rather than directly awaited?

References

  • Async Book
  • Tokio Documentation