Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

The Standard Library as the Async Contract

Tokio’s public foundation comes from std, not from a special async language runtime.

Future, Poll, and Context

A future exposes one operation:

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>

Ready(output) transfers a result. Pending promises that the future arranged for a relevant waker to be notified. Returning Pending without arranging a wake can leave a task dormant forever.

Pin

Compiled async state machines can contain references into their own stored state. Pin<&mut T> prevents safe code from moving such a future after polling begins. Tokio’s intrusive timer and waiter lists also rely on stable addresses.

Waker

A Waker is an owned, thread-safe callback-like handle. Tokio implements its RawWakerVTable using the task header: clone changes the reference count; wake changes notification state and schedules if necessary; drop releases a task reference.

Atomics encode the task lifecycle

One AtomicUsize packs running, complete, notified, cancelled, join-interest, join-waker, and reference-count state. Atomic read-modify-write transitions establish one order for races among polling, waking, joining, cancellation, and shutdown.

Arc, Mutex, and UnsafeCell

Shared scheduler and I/O structures use Arc; infrequent compound state uses locks; fields with access guaranteed by atomic protocol use UnsafeCell. unsafe does not remove synchronization—it lets Tokio express a verified synchronization rule the compiler cannot infer.

Drop

Dropping a future after cancellation runs its local destructors. Dropping registrations clears stored wakers to break cycles. Dropping runtime ownership initiates scheduler, driver, and blocking-pool teardown.

Application authors mostly see safe futures because Tokio concentrates these low-level invariants behind a narrow runtime task abstraction.