Lesson 24 of 26
async/await vs asyncio
Async code lets one program wait for many slow things at once, such as network calls, without a thread for each.
Python does this with asyncio: async def, await, and an event loop started by
asyncio.run. Rust's version reads almost the same: async fn and .await.
The big difference: Rust's standard library has no event loop. It only defines what a future is (a piece
of work that can pause). To run futures you add a runtime crate, and almost all real code uses
tokio. So most async Rust you read starts with #[tokio::main] and calls things like
tokio::spawn and tokio::time::sleep.
For reading code, map it like this:
async fn=async def, andx.await=await x(the.awaitgoes after).#[tokio::main]=asyncio.run(main()).tokio::join!=asyncio.gather, andtokio::spawn=asyncio.create_task.tokio::time::timeout=asyncio.wait_for, andtokio::select!= "wait for whichever finishes first".
async def becomes async fn
The shape is the same: an async function that waits, and a main that awaits it. Two things
move. .await goes after the call, so you can chain it: fetch().await.len(). And
asyncio.run(main()) becomes the #[tokio::main] line above main.
import asyncio
async def greet(name):
await asyncio.sleep(0.01)
return f"hello {name}"
async def main():
message = await greet("ada")
print(message)
asyncio.run(main())use std::time::Duration;
async fn greet(name: &str) -> String {
tokio::time::sleep(Duration::from_millis(10)).await;
format!("hello {name}")
}
#[tokio::main]
async fn main() {
let message = greet("ada").await;
println!("{message}");
}hello adaCalling an async function does nothing yet
Here Python and Rust agree. Calling an async function doesn't run its body. It gives back a paused piece
of work: a coroutine in Python, a future in Rust. The body only runs when you await it. That is why
both print created the job before working.
import asyncio
async def work():
print("working")
return 1
async def main():
job = work()
print("created the job")
result = await job
print(f"result: {result}")
asyncio.run(main())async fn work() -> i32 {
println!("working");
1
}
#[tokio::main]
async fn main() {
let job = work();
println!("created the job");
let result = job.await;
println!("result: {result}");
}created the job
working
result: 1Run several at once: tokio::join! and asyncio.gather
Each call waits 50 ms. To show that they really wait at the same time, without timing anything, each
call counts how many calls are running at that moment. Awaiting them one by one would never have more than 1
running. asyncio.gather and tokio::join! start all three before any of them finishes. The
results come back in the order you wrote the calls, not the order they finished.
import asyncio
running = 0
most = 0
async def fetch(name):
global running, most
running += 1
most = max(most, running)
await asyncio.sleep(0.05)
running -= 1
return f"{name} done"
async def main():
users, orders, prices = await asyncio.gather(fetch("users"), fetch("orders"), fetch("prices"))
print(f"{users}, {orders}, {prices}")
print(f"at most {most} running at once")
asyncio.run(main())use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
static RUNNING: AtomicUsize = AtomicUsize::new(0);
static MOST: AtomicUsize = AtomicUsize::new(0);
async fn fetch(name: &str) -> String {
let now = RUNNING.fetch_add(1, Ordering::SeqCst) + 1;
MOST.fetch_max(now, Ordering::SeqCst);
tokio::time::sleep(Duration::from_millis(50)).await;
RUNNING.fetch_sub(1, Ordering::SeqCst);
format!("{name} done")
}
#[tokio::main]
async fn main() {
let (users, orders, prices) = tokio::join!(fetch("users"), fetch("orders"), fetch("prices"));
println!("{users}, {orders}, {prices}");
println!("at most {} running at once", MOST.load(Ordering::SeqCst));
}users done, orders done, prices done
at most 3 running at onceTasks: tokio::spawn and asyncio.create_task
join! runs futures inside the current task. tokio::spawn makes each future its own
task that runs by itself, like asyncio.create_task, and gives you a handle to await later. One
difference: asyncio runs everything on one thread, but tokio spreads tasks over several threads. So, just like
thread::spawn in lesson 22, a spawned future must own its data ('static) and be safe to
move to another thread (Send).
import asyncio
async def square(n):
await asyncio.sleep(0.01)
return n * n
async def main():
tasks = [asyncio.create_task(square(n)) for n in [1, 2, 3]]
results = [await t for t in tasks]
print(results)
asyncio.run(main())use std::time::Duration;
async fn square(n: i32) -> i32 {
tokio::time::sleep(Duration::from_millis(10)).await;
n * n
}
#[tokio::main]
async fn main() {
let mut handles = Vec::new();
for n in [1, 2, 3] {
handles.push(tokio::spawn(square(n)));
}
let mut results = Vec::new();
for h in handles {
results.push(h.await.unwrap());
}
println!("{:?}", results);
}[1, 4, 9]Timeouts: tokio::time::timeout and asyncio.wait_for
slow() needs a second, but we only give it 50 ms. Python raises TimeoutError.
Rust's timeout returns a Result instead: Ok with the value, or
Err if time ran out. The slow future is then simply dropped, and dropping a future stops it.
tokio::select!, which you'll also see in real code, works the same way: it waits for whichever
branch finishes first and drops the others.
import asyncio
async def slow():
await asyncio.sleep(1)
return "finished"
async def main():
try:
result = await asyncio.wait_for(slow(), timeout=0.05)
print(result)
except TimeoutError:
print("gave up after 50 ms")
asyncio.run(main())use std::time::Duration;
use tokio::time::{sleep, timeout};
async fn slow() -> String {
sleep(Duration::from_secs(1)).await;
String::from("finished")
}
#[tokio::main]
async fn main() {
match timeout(Duration::from_millis(50), slow()).await {
Ok(result) => println!("{result}"),
Err(_) => println!("gave up after 50 ms"),
}
}gave up after 50 msWhere the Python analogy breaks
- Async needs a runtime crate. Python ships an event loop in
asyncio. Rust's standard library only defines futures;#[tokio::main]is what starts a runtime to run them. - tokio uses several threads. asyncio runs all coroutines on one thread, but tokio spreads tasks over a thread pool by
default. That's why
tokio::spawnneedsSend + 'staticfutures, likethread::spawnin lesson 22. - A forgotten
.awaitis caught early. Python warns at run time that a "coroutine was never awaited". rustc warns at compile time ("unused implementer ofFuturethat must be used"), and using the result as a value doesn't compile at all. - Cancelling is dropping. Python raises
CancelledErrorinside a cancelled task, so it can clean up inexceptorfinally. In Rust,timeoutandselect!just drop the future: it stops at its current.await, and only itsDropcode runs. - Blocking still blocks.
std::thread::sleep, a slow file read withstd::fs, or heavy CPU work inside anasync fnstalls other tasks, just liketime.sleepin anasync def. Usetokio::time::sleep,tokio::fs, ortokio::task::spawn_blocking.
Cheat card
| Python | Rust |
|---|---|
asyncio.run(main()) | #[tokio::main]
async fn main() { } |
async def f(): ... | async fn f() { } |
await f() | f().await |
await asyncio.sleep(0.5) | tokio::time::sleep(Duration::from_millis(500)).await; |
await asyncio.gather(a(), b()) | tokio::join!(a(), b()) |
task = asyncio.create_task(f()) | let handle = tokio::spawn(f()); |
await task | handle.await.unwrap() |
await asyncio.wait_for(f(), timeout=1) | tokio::time::timeout(Duration::from_secs(1), f()).await |
asyncio.wait(..., return_when=FIRST_COMPLETED) | tokio::select! { ... } |
await asyncio.to_thread(blocking) | tokio::task::spawn_blocking(blocking).await |
except asyncio.CancelledError: | // no exception: a dropped future just stops |
← The crates you'll meet everywhere Rust inside Python with PyO3 →