Skip to content
RustLearn

Module 18 Exercises — Async Rust

How to use this page

Attempt every exercise in a real Cargo project before opening a solution — a solution you have not fought for teaches almost nothing. Tick the boxes as you go; progress is saved in this browser.

Before you start, be able to explain:

  • why async helps a web server and not an image encoder;
  • what calling an async fn without .await actually produces;
  • why tokio::join! can be twice as fast as two sequential awaits.

Time the drills. The difference between sequential and concurrent awaits is the kind of thing that is obvious once you have measured it yourself and abstract forever if you have not.

Part A — Warm-Up Drills

Short reps on the mechanics. Do them until the syntax stops costing you any thought.

🟢 Exercise 18.1 — Sequential vs concurrent

Write async fn work(id: u32, ms: u64) -> u32 that sleeps and returns id. Call three of them sequentially and time it; then with join! and time it. Report both.

Solution
rust
use std::time::{Duration, Instant};
use tokio::time::sleep;

async fn work(id: u32, ms: u64) -> u32 {
    sleep(Duration::from_millis(ms)).await;
    id
}

#[tokio::main]
async fn main() {
    let t = Instant::now();
    let (a, b, c) = (work(1, 100).await, work(2, 100).await, work(3, 100).await);
    println!("sequential: {a}{b}{c} in {:?}", t.elapsed());       // ~300ms

    let t = Instant::now();
    let (a, b, c) = tokio::join!(work(1, 100), work(2, 100), work(3, 100));
    println!("concurrent: {a}{b}{c} in {:?}", t.elapsed());       // ~100ms
}

🟢 Exercise 18.2 — Spot the bug

What's wrong with each?

rust
// A
async fn a() { std::thread::sleep(Duration::from_secs(1)); }

// B
async fn b() {
    let fut = fetch_data(1);
    println!("started");
}

// C
async fn c(m: Arc<std::sync::Mutex<i32>>) {
    let g = m.lock().unwrap();
    other().await;
}
Answers
  • A: blocks the whole executor thread; use tokio::time::sleep(..).await.
  • B: the future is never awaited, so nothing runs (and you get an unused_must_use warning).
  • C: holds a non-Send MutexGuard across an .await; the future won't be Send and you risk deadlock. Read the value into a local and drop the guard first.

Part B — Core Exercises

The real practice. Attempt each one fully — compiler errors included — before opening a solution.

🟡 Exercise 18.3 — Concurrent fetch with limit

Fetch 20 simulated URLs but with at most 5 in flight at a time, using a tokio::sync::Semaphore. Print results as they complete.

Solution
rust
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Semaphore;
use tokio::time::sleep;

async fn fetch(id: u32) -> String {
    sleep(Duration::from_millis(100)).await;
    format!("result {id}")
}

#[tokio::main]
async fn main() {
    let sem = Arc::new(Semaphore::new(5));
    let mut handles = vec![];

    for id in 0..20 {
        let sem = Arc::clone(&sem);
        handles.push(tokio::spawn(async move {
            let _permit = sem.acquire().await.unwrap();   // released on drop
            fetch(id).await
        }));
    }

    for h in handles {
        println!("{}", h.await.unwrap());
    }
}

Total time is ~400ms (4 batches of 5) rather than 100ms or 2000ms.

🟡 Exercise 18.4 — select! and cancellation

Write a task that repeatedly emits a tick every 100ms, and a select! loop in main that prints ticks until either 10 have arrived or a 700ms deadline passes — whichever comes first.

Solution
rust
use std::time::Duration;
use tokio::sync::mpsc;
use tokio::time::{sleep, Instant};

#[tokio::main]
async fn main() {
    let (tx, mut rx) = mpsc::channel::<u32>(8);

    tokio::spawn(async move {
        for i in 0.. {
            if tx.send(i).await.is_err() { break; }
            sleep(Duration::from_millis(100)).await;
        }
    });

    let deadline = sleep(Duration::from_millis(700));
    tokio::pin!(deadline);                 // needed to poll it repeatedly in select!

    let mut count = 0;
    loop {
        tokio::select! {
            Some(tick) = rx.recv() => {
                println!("tick {tick}");
                count += 1;
                if count == 10 { println!("got 10 ticks"); break; }
            }
            _ = &mut deadline => { println!("deadline reached after {count} ticks"); break; }
        }
    }
}

tokio::pin! is required because select! needs &mut deadline across loop iterations, and futures must be pinned to be polled more than once.

Part C — Challenges

Longer builds. Expect to fight the borrow checker here; that fight is the lesson.

🔴 Exercise 18.5 — Async job queue with graceful shutdown

Build a worker pool of 4 async tasks pulling jobs from a shared Arc<Mutex<VecDeque<Job>>> or a mpsc channel, where:

  • each job simulates variable-duration I/O
  • a broadcast channel signals shutdown
  • workers finish their current job, then exit cleanly
  • main reports how many jobs each worker completed
Solution
rust
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{broadcast, mpsc, Mutex};
use tokio::time::sleep;

#[derive(Debug)]
struct Job { id: u32, ms: u64 }

#[tokio::main]
async fn main() {
    let (job_tx, job_rx) = mpsc::channel::<Job>(100);
    let job_rx = Arc::new(Mutex::new(job_rx));
    let (shutdown_tx, _) = broadcast::channel::<()>(1);

    let workers: Vec<_> = (0..4).map(|wid| {
        let rx = Arc::clone(&job_rx);
        let mut shutdown = shutdown_tx.subscribe();
        tokio::spawn(async move {
            let mut done = 0u32;
            loop {
                let job = {
                    let mut guard = rx.lock().await;
                    tokio::select! {
                        j = guard.recv() => j,
                        _ = shutdown.recv() => None,
                    }
                };                                   // guard dropped here
                match job {
                    Some(j) => {
                        sleep(Duration::from_millis(j.ms)).await;
                        println!("worker {wid} finished job {}", j.id);
                        done += 1;
                    }
                    None => break,
                }
            }
            (wid, done)
        })
    }).collect();

    for id in 0..12 {
        job_tx.send(Job { id, ms: 50 + (id as u64 % 4) * 30 }).await.unwrap();
    }

    sleep(Duration::from_millis(400)).await;
    println!("--- shutting down ---");
    let _ = shutdown_tx.send(());
    drop(job_tx);

    for w in workers {
        let (wid, done) = w.await.unwrap();
        println!("worker {wid} completed {done} jobs");
    }
}

The important detail is the inner block: the mutex guard is released before the job runs, so the four workers actually process jobs concurrently rather than serializing on the queue lock — the async version of the same lesson from module 17's thread pool.

Self-check

  1. What happens when you call an async fn without awaiting it?
  2. Why is async better than threads for 10,000 concurrent HTTP requests?
  3. What does .await do to the current thread?
  4. Why must CPU-heavy work go through spawn_blocking?
  5. When should you use tokio::sync::Mutex over std::sync::Mutex?
Answers
  1. Nothing — you get a lazy Future that does no work until polled.
  2. Each async task costs hundreds of bytes and no kernel context switch, versus ~8 KB of stack and a syscall per blocked thread.
  3. Yields it back to the runtime so other tasks can run; it does not block.
  4. A long synchronous call occupies an executor thread, starving every other task scheduled on it.
  5. Only when you must hold the lock across an .await point.

Next: Module 19 — Macros, Unsafe & FFI