Channels in Rust
mpsc moves values between threads: many senders, one receiver.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
for id in 0..3 {
let tx = tx.clone();
thread::spawn(move || {
tx.send(format!("worker {id} finished")).unwrap();
});
}
drop(tx);
for message in rx {
println!("{message}");
}
}
How it works
- Each thread gets its own clone of the sender.
- The receiver iterates until every sender is dropped.
- Values are moved, so there is nothing to lock.
Keywords and builtins used here
dropfnforinletmainmoveuse
The run, in numbers
- Lines
- 18
- Characters to type
- 260
- Tokens
- 93
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 53 seconds.
Step 1 of 2 in Channels, step 7 of 15 in Concurrency & async.