mpsc Channels
Send between threads.
What Is a Channel?
A channel is a one-way pipe for sending values from one thread to another. Rust's standard library provides std::sync::mpsc where mpsc means multiple producer, single consumer.
- The Sender half pushes values in.
- The Receiver half pulls values out.
Channels let threads communicate by passing messages instead of sharing memory directly, which avoids many data races.
Creating a Channel
Call mpsc::channel() to get a tuple of (Sender, Receiver). Here we send one value from a spawned thread back to the main thread.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
tx.send(42).unwrap();
});
let received = rx.recv().unwrap();
println!("Got: {}", received);
}