Module 7Threads & ChannelsLesson 2 of 722 min
Channels (mpsc)
Message passing between workers and aggregator.
channel
rust
use std::sync::mpsc;
let (tx, rx) = mpsc::channel();
tx.send(1).unwrap();
let n = rx.recv().unwrap();Clone Sender
Each worker gets tx.clone(). Drop original tx so rx finishes.
Prefer messages
Often simpler than shared mutability for MC aggregation.
Challenge
Send (thread_id, sum) tuples and print per worker.
Tips
- Clone Sender per worker
- drop(tx) closes channel
- recv blocks; iter ends when closed
Try it live
Channels (mpsc)Rust 2021
Loading editor…
Output
Press Run to compile and execute.