Working with Futures and Tasks
Understand the `Future` trait and how tasks are scheduled and managed within an asynchronous runtime environment.
What is a Rust Future?
In asynchronous Rust, a Future is a trait that represents an asynchronous computation which may complete at some point. Think of it as a promise for a value that isn't ready yet.
- It's the core building block for async Rust.
async fns in Rust actually return an anonymous type that implements theFuturetrait.- The value isn't computed immediately; it's computed when the
Futureis "polled" by an executor.
How Futures Make Progress
A Future doesn't run on its own. An executor (like the Tokio runtime) repeatedly "polls" it to check if it has made progress or completed.
- When polled, a
Futurereturns eitherPoll::Pending(not done yet) orPoll::Ready(T)(done, here's the result). - If
Pending, the executor knows to poll it again later when something relevant happens (e.g., I/O finishes). - This polling mechanism is what allows many asynchronous operations to run concurrently on a single thread.
All lessons in this course
- Introduction to Async/Await
- Building Async Applications with Tokio
- Working with Futures and Tasks