Actor-style concurrency following the philosophy: Do not communicate by sharing memory; share memory by communicating.
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::channel();
for id in 0..3 {
let thread_tx = tx.clone();
thread::spawn(move || {
thread_tx.send(format!("Job #{} completed", id)).unwrap();
});
}
drop(tx); // Drop original sender so receiver knows when stream ends!
for msg in rx { // Iterates until all tx handles are dropped
println!("Worker event: {}", msg);
}
}Channels decouple producers and consumers, eliminating the need for shared mutable state and complex explicit mutex locking.
When a sender transmits a value over a channel (`tx.send(val)`), ownership of `val` is transferred across the thread boundary. The sender can no longer access `val`.
When all `Sender` instances are dropped, the channel automatically closes, allowing the receiver's iterator loop to terminate cleanly.
In high-throughput microservices, unbounded queues risk Out-Of-Memory (OOM) crashes if producers outpace consumers. `sync_channel(bound)` blocks `send()` until queue slots free up.
let (tx, rx) = mpsc::sync_channel(2);
tx.send("A").unwrap(); // Ok
tx.send("B").unwrap(); // Ok
// tx.send("C").unwrap(); // Blocks until rx.recv() is called!