Rust

tokio mpsc Channel

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Async multi-producer / single-consumer channel. Producers `.send()`, the single receiver `.recv().await` items as they arrive. Bounded — the channel back-pressures producers when full.
Rust
Raw
use tokio::sync::mpsc;

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

    // Spawn 3 producers
    for i in 0..3 {
        let tx = tx.clone();
        tokio::spawn(async move {
            for j in 0..4 {
                tx.send(format!("p{i}-msg{j}")).await.unwrap();
            }
        });
    }
    drop(tx);                              // drop the original — when all clones drop, rx closes

    // Single consumer drains until the channel closes
    while let Some(msg) = rx.recv().await {
        println!("got: {msg}");
    }
    println!("channel closed");
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.