Rust for Pythonistas

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, and x.await = await x (the .await goes after).
  • #[tokio::main] = asyncio.run(main()).
  • tokio::join! = asyncio.gather, and tokio::spawn = asyncio.create_task.
  • tokio::time::timeout = asyncio.wait_for, and tokio::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.

Python
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())
Rust
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}");
}
Output
hello ada

Calling 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.

Python
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())
Rust
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}");
}
Output
created the job
working
result: 1

Run 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.

Python
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())
Rust
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));
}
Output
users done, orders done, prices done
at most 3 running at once

Tasks: 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).

Python
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())
Rust
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);
}
Output
[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.

Python
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())
Rust
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"),
    }
}
Output
gave up after 50 ms

Where the Python analogy breaks

Cheat card

PythonRust
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 taskhandle.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 →