Rust Message Passing Channels
Threads must exchange information to cooperate. One safe approach copies the idea of a postal system: a thread drops a message in a mailbox, and another thread picks it up. Rust offers this through channels. The standard motto from the Go community captures the spirit: share memory by communicating instead of communicating by sharing memory.
Channel Anatomy
A channel has two ends. The transmitter sends messages, and the receiver collects them.
Thread A Thread B +----------+ +-------------+ +----------+ | tx |---->| (queue) |---->| rx | | (sender) | | messages | |(receiver)| +----------+ +-------------+ +----------+
The module std::sync::mpsc provides channels. The letters stand for multiple producer, single consumer: many senders, one receiver.
A First Channel
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
tx.send(String::from("hello from the worker")).unwrap();
});
let message = rx.recv().unwrap();
println!("Got: {message}");
}
Got: hello from the worker
The move keyword hands the transmitter to the new thread. The main thread keeps the receiver and waits inside recv until a message arrives.
Sending Moves Ownership
A sent value moves into the channel. The sender cannot touch it afterward. The rule prevents two threads from changing the same data at once.
let text = String::from("report");
tx.send(text).unwrap();
// println!("{text}"); // error: value movedSending Many Messages
The receiver works as an iterator. A for loop prints each message and stops once every sender has finished.
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
for i in 1..=3 {
tx.send(format!("step {i}")).unwrap();
thread::sleep(Duration::from_millis(100));
}
});
for message in rx {
println!("{message}");
}
}
step 1 step 2 step 3
Receiving Methods
| Method | Behavior |
|---|---|
| recv() | Waits until a message arrives or all senders close |
| try_recv() | Checks right away and never waits |
| recv_timeout(duration) | Waits up to a time limit |
Use try_recv when the thread has other work to do between checks.
Several Producers
Clone the transmitter to give each worker its own sending end. All messages flow into one receiver.
fn main() {
let (tx, rx) = mpsc::channel();
for id in 1..=3 {
let tx_clone = tx.clone();
thread::spawn(move || {
tx_clone.send(format!("worker {id} finished")).unwrap();
});
}
drop(tx); // close the original sender
for message in rx {
println!("{message}");
}
}
worker 1 --tx--+ worker 2 --tx--+--> one receiver --> main thread worker 3 --tx--+
The drop(tx) line matters. The receiving loop ends only after every transmitter, including the original, goes away. Forgetting that line leaves the loop waiting forever.
Message order between different workers depends on thread timing, so the lines may print in any sequence.
Handling Closed Channels
A send fails when the receiver is gone, and a receive fails when every sender is gone. Both methods return a Result, so a robust program matches on it instead of calling unwrap.
match rx.recv() {
Ok(msg) => println!("{msg}"),
Err(_) => println!("All senders have closed"),
}Sending Structured Data
Channels carry any type, including enums. An enum lets one channel deliver several kinds of commands.
enum Command {
Print(String),
Stop,
}
let (tx, rx) = mpsc::channel();
tx.send(Command::Print(String::from("hi"))).unwrap();
tx.send(Command::Stop).unwrap();
for cmd in rx.try_iter() {
match cmd {
Command::Print(t) => println!("{t}"),
Command::Stop => break,
}
}When Channels Fit
- Pipelines where one stage hands work to the next
- Worker pools that report results to a coordinator
- Background tasks that send progress updates
- Programs that need clear ownership of data at each moment
Key Points
mpsc::channel()returns a transmitter and a receiver.- Sending moves ownership of the value.
- Clone
txfor multiple producers, and drop the original when finished. - The receiver works inside a
forloop until all senders close.
