Sub topic 1
What async fn and .await actually give you
An async fn does not run when you call it. It builds a value that can run later, and .await is the point where that value gets driven forward. This chapter explains what that means in practice, so that later chapters on polling, runtimes and tasks have something solid to build on.
Prerequisites
This chapter assumes you already know:
- Rust ownership, borrowing and lifetimes, including why a value can't be used after it moves.
- Traits, generics and closures, including
impl Traitin return position. - Basic Cargo use: adding a dependency and running
cargo run. - Threads with
ArcandMutexfromstd(helpful, not required).
To run the examples, add Tokio to Cargo.toml:
[dependencies]
tokio = { version = "1", features = ["full"] }Tokio appears here only so the examples have somewhere to run. The runtime itself is covered in later chapters.
An async fn returns a future
Calling an async fn produces a value that implements the Future trait. The function body has not started. The compiler treats these two declarations as nearly the same:
async fn double(x: u32) -> u32 {
x * 2
}
fn double_desugared(x: u32) -> impl std::future::Future<Output = u32> {
async move { x * 2 }
}
#[tokio::main]
async fn main() {
println!("{}", double(4).await);
println!("{}", double_desugared(5).await);
}The return type is an anonymous type chosen by the compiler. Its Output associated type is the value the function eventually produces. You can't name the type, but you can rely on it being a Future.
An async { ... } block works the same way. It creates a future from a chunk of code, and async move moves the captured variables into that future.
Futures are lazy
A future does nothing until something polls it. The next program shows the order of events:
async fn greet() -> &'static str {
println!("running greet");
"hello"
}
#[tokio::main]
async fn main() {
let fut = greet();
println!("created the future");
let msg = fut.await;
println!("{msg}");
}The output is:
created the future
running greet
helloThe line running greet appears only after .await. If you drop fut without awaiting it, greet never runs. Rust warns about this with unused_must_use, because futures are marked #[must_use]. Treat that warning as an error. A missing .await is one of the most common async bugs, and the code still compiles.
What .await does
.await can only appear inside an async context. It does two things:
- It drives the inner future until it either finishes or can't make progress yet.
- If it can't make progress (for example, a timer hasn't fired), it suspends the current future and gives control back to whoever is driving it. When the inner future is ready, the outer one resumes exactly where it stopped.
Suspension is cooperative. A future gives up control only at an .await point. Between two .awaits, your code runs without interruption until the next one, and nothing can preempt it. This matters later, when we look at blocking code.
The compiler builds a state machine
Each async fn becomes a state machine. Every .await is a point where the machine can pause, and the locals still needed after that point are stored inside the future itself. Roughly, a function with two awaits has these states:
Three consequences follow from this:
- No stack per future. A future is an ordinary value whose size is the largest set of data it must keep across its awaits. Thousands of them are cheap.
- Moves are fine before the first poll. After polling begins, a future may contain references into itself, so it must stay put. That is why the
Pintype exists. You will see it in the next chapter. - Large locals held across an
.awaitmake the future large. A big array alive across an await point is stored in the future, and moving that future copies the array.
Awaiting is sequential by default
Many newcomers assume .await means "run this in the background". It means the opposite: this function waits here until the inner future is done. Two awaits in a row run one after another:
use std::time::{Duration, Instant};
use tokio::time::sleep;
async fn step(ms: u64) -> u64 {
sleep(Duration::from_millis(ms)).await;
ms
}
#[tokio::main]
async fn main() {
let start = Instant::now();
let a = step(100).await;
let b = step(100).await;
let elapsed = start.elapsed();
println!("sum = {}, took at least 200 ms: {}", a + b, elapsed >= Duration::from_millis(200));
}The two waits add up. async gives you the ability to pause without blocking a thread. It does not give you concurrency until you ask for it, which you do by running several futures together. That is the subject of later chapters, with tokio::join! for futures inside one task and tokio::spawn for separate tasks.
What async does not give you
| Belief | Reality |
|---|---|
| Calling an async function starts work | It only creates the future. Work starts at the first poll. |
| `.await` runs things in parallel | `.await` waits. Parallelism needs `spawn` or a multi-threaded runtime. |
| Async code makes CPU work faster | It helps only when tasks spend time waiting (network, timers, disk). |
| Async code never blocks | A blocking call inside async code blocks the thread that is driving it. |
| A future runs by itself | Something must poll it. The language provides no built-in executor. |
The last row is the key one. The Rust standard library defines Future and the async/.await syntax, but it ships no runtime. A crate such as Tokio provides the part that actually polls futures. A plain fn main can't use .await for that reason, and #[tokio::main] exists to bridge that gap.
Common errors
Forgetting .await. The compiler warns unused implementer of Future that must be used, and the work silently never happens. When you see this warning, you almost always want to add .await.
Using .await in a non-async function. The error is `error[E0728]: await is only allowed inside async functions and blocks. Either make the caller async` or hand the future to a runtime.
Holding a non-Send value across an .await. Futures that capture Rc or a std::sync::MutexGuard across a suspension point are not Send. They can't be moved to another worker thread, so tokio::spawn rejects them. The fix is usually to end the value's scope before the .await:
use std::sync::{Arc, Mutex};
use tokio::time::{sleep, Duration};
#[tokio::main]
async fn main() {
let data = Arc::new(Mutex::new(1u32));
let value = {
let guard = data.lock().unwrap();
*guard
}; // guard is dropped here, before the await
sleep(Duration::from_millis(10)).await;
println!("{value}");
}Blocking inside async code. Calling std::thread::sleep or a long CPU loop inside an async fn stalls the whole thread, and every other future scheduled on it. Use tokio::time::sleep for waiting, and spawn_blocking for heavy work, covered in a later chapter.
Summary of the working model
async fnreturns a lazy value that implementsFuture..awaitdrives that value and suspends the caller if the value isn't ready.- Suspension happens only at
.awaitpoints, so the code between them is never interrupted. - The compiler turns each async body into a state machine, which stores the locals it needs across awaits.
- Sequential awaits take as long as the sum of their parts. Overlap needs explicit combinators or tasks.
- A runtime is a separate component that polls futures. The next chapters explain how.
Exercise
In the program below, what does it print, and in what order? Then say what changes if you delete .await from the last line of main.
async fn load() -> u32 {
println!("loading");
7
}
#[tokio::main]
async fn main() {
let f = load();
println!("before");
let n = f.await;
println!("after {n}");
}
Show answer
It prints "before", then "loading", then "after 7". The call load() only creates the future, so "loading" prints when f.await first drives it. This program already has .await on f, so deleting the .await from its last line (println!("after {n}")) is not possible. The question applies to let n = f.await;. If you remove .await there, n would be the future itself. The code would then fail to compile, because the future does not implement Display. If you instead write let _ = f; and never await it, "loading" never prints, and the compiler warns that the future is unused.
Exercise
Two calls to step(100).await run one after the other, as in the timing example. Why does this take about 200 ms and not 100 ms, and what kind of change would let the waits overlap?
Show answer
Each .await waits for its future to finish before the next line runs, so the waits add up to about 200 ms. The waits overlap if both futures are run together, for example with tokio::join!(step(100), step(100)) inside one task, or by spawning each with tokio::spawn and awaiting the handles. Either way, the total drops to about 100 ms.