Rust

mpsc Channel Between Threads

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`std::sync::mpsc` is the standard cross-thread channel. Multiple producers, single consumer. Send any `Send` type; the receiver blocks on `recv()` until something arrives.
Rust
Raw
use std::sync::mpsc;
use std::thread;
use std::time::Duration;

fn main() {
    let (tx, rx) = mpsc::channel::<String>();

    // Three producers — clone tx for each
    for i in 0..3 {
        let tx = tx.clone();
        thread::spawn(move || {
            for j in 0..3 {
                tx.send(format!("from {i}: msg {j}")).unwrap();
                thread::sleep(Duration::from_millis(10));
            }
        });
    }
    drop(tx);                        // close the original — receiver loop ends when all clones drop

    for msg in rx {                  // iterator form — yields until channel closes
        println!("got: {msg}");
    }
    println!("done");
}
Tags

Save your own code snippets

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