Sub topic 1
What `async fn` and `.await` Actually Give You
Prerequisites
Assume you know Rust ownership, borrowing, lifetimes, traits, closures, and basic Cargo usage. Familiarity with threads and Arc<Mutex<T>> is helpful.
`async fn` Creates a Future
An async fn does not run its body immediately. It returns a future, a value that represents work that may finish later. Calling the function creates the future. The future starts doing work only when an executor polls it.
.await tells the current future to pause until another future makes progress. While paused, the task can give the thread to other work.
use std::time::Duration;
use tokio::time::sleep;
async fn answer() -> u32 {
sleep(Duration::from_millis(100)).await;
42
}
#[tokio::main]
async fn main() {
let value = answer().await;
println!("{value}");
}How Futures Are Polled
A future implements the Future trait. Its poll method returns either:
Poll::Ready(value)when the work is complete.Poll::Pendingwhen it cannot continue yet.
When a future returns Pending, it registers a waker. The waker tells the executor to poll the future again when an event occurs, such as a socket becoming readable or a timer expiring.
What a Runtime Adds
A Tokio runtime combines an executor and a reactor. The executor schedules and polls tasks. The reactor listens for operating-system events, such as network readiness and timer expiration, then wakes the relevant tasks.
Starting Tokio and Choosing a Runtime
#[tokio::main] generates a synchronous main function that creates a runtime and runs your asynchronous main body.
Tokio’s default flavor is multi-threaded. It uses several worker threads and can run tasks in parallel. The current-thread flavor uses one thread. It is useful for small programs or tests, but blocking work can stop every task.
Spawning Concurrent Tasks
tokio::spawn schedules a future as an independent task and returns a JoinHandle. The spawned future must usually be Send + 'static, because Tokio may move it between worker threads and it must not borrow a stack local that could disappear.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
sleep(Duration::from_millis(100)).await;
42
});
println!("result = {}", handle.await.unwrap());
}Exercise
Does calling an async fn execute its body immediately?
Show answer
No. It creates a future. The body runs when an executor polls that future.