Producer Consumer With Channels
Send messages from producer threads to a consumer over an mpsc channel, letting the receiver drain work without shared mutable state.
Code
use std::sync::mpsc;
use std::thread;
fn main() {
let (sender, receiver) = mpsc::channel::<u32>();
let producers: Vec<_> = (0..3)
.map(|id| {
let sender = sender.clone();
thread::spawn(move || {
for item in 1..=3 {
sender.send(id * 10 + item).expect("send failed");
}
})
})
.collect();
drop(sender);
let consumer = thread::spawn(move || {
let mut total = 0u32;
while let Ok(value) = receiver.recv() {
total += value;
}
total
});
for handle in producers {
handle.join().expect("producer panicked");
}
let total = consumer.join().expect("consumer panicked");
println!("total = {total}");
}Inside the snippet
Producer Consumer With Channels comes down to the function main.
Repetition is confined to for item in 1..=3 — the rest of the file is straight-line.
Putting it to use
The demo output is labeled (total =), so every printed line maps back to its originating operation.
Core lines
while let Ok(value) = receiver.recv() {
total += value;
}
thread::spawn(move || {
for item in 1..=3 {
sender.send(id * 10 + item).expect("send failed");
}
})
Interactive Tools for This Topic
FAQ
- What does Producer Consumer With Channels print when run?
- Execute the whole file; each printed line is prefixed with a label like `total =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.