typestar

Async channels in Rust

tokio's mpsc is the async twin of the std channel: send and recv both await.

use tokio::sync::mpsc;

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

    for id in 0..3 {
        let tx = tx.clone();
        tokio::spawn(async move {
            tx.send(format!("job {id} done")).await.unwrap();
        });
    }
    drop(tx);

    while let Some(message) = rx.recv().await {
        println!("{message}");
    }
}

How it works

  1. channel(n) bounds the queue, applying backpressure.
  2. recv returns None once every sender is dropped.
  3. The producer and consumer are ordinary tasks.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
306
Tokens
110
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 60 seconds.

Type this snippet

Step 5 of 6 in Async with tokio, step 13 of 15 in Concurrency & async.

← Previous Next →