Send the work, not a shared mess.
Coordinate threads with explicit messages and closure.
01 Understand the contract
A channel transfers messages between a sender and a receiver. std::sync::mpsc provides multiple producers and one receiver; sending an owned value moves it. The receiving iterator ends when every sender is dropped, so keeping an unused sender alive can accidentally block shutdown. sync_channel adds bounded capacity and backpressure, while channel is unbounded. Choose capacity and overload behavior deliberately rather than letting a fast producer grow memory without limit.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
use std::{sync::mpsc, thread};
fn main() {
let (tx, rx) = mpsc::sync_channel(2);
let worker = thread::spawn(move || {
for n in 1..=3 {
tx.send(n).unwrap();
}
});
let total: i32 = rx.iter().sum();
worker.join().unwrap();
println!("total={total}");
}total=6
- 1
The bounded channel can hold at most two waiting messages.
- 2
The producer drops its sender when it returns.
- 3
The receiver’s iterator finishes after queued messages drain and all senders are gone.
cargo run -p lesson_channels03 Mind the boundary
04 Your next build
Send three strings from a worker and collect them in order on the receiving thread.
Reveal one possible solution +
use std::{sync::mpsc, thread};
fn main() {
let (tx, rx) = mpsc::channel();
let h = thread::spawn(move || {
for s in ["plan", "build", "test"] {
tx.send(s.to_owned()).unwrap();
}
});
let result: Vec<_> = rx.iter().collect();
h.join().unwrap();
assert_eq!(result, ["plan", "build", "test"]);
}05 Check your reasoning
When does rx.iter() finish after the queue drains?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.