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
channel(n)bounds the queue, applying backpressure.recvreturnsNoneonce every sender is dropped.- The producer and consumer are ordinary tasks.
Keywords and builtins used here
SomeStringasyncawaitdropfnforinletmainmovemutusewhile
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.
Step 5 of 6 in Async with tokio, step 13 of 15 in Concurrency & async.