Sub topic 2
Sending Messages with Channels
Assume you know Rust ownership, closures, Result, and basic thread creation. A channel is a one-way queue for sending values between threads. Rust’s std::sync::mpsc channel means “multiple producer, single consumer”: several Sender values can send, but one Receiver reads.
Sending Messages
Create a channel with mpsc::channel. send transfers ownership of its value. The receiver gets the value through recv.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
for i in 0..3 {
tx.send(i).unwrap();
}
});
for value in rx {
println!("got {value}");
}
}The move closure takes ownership of tx, so the sender can live for the entire spawned thread. The receiving for loop waits for messages and stops when the channel closes.
Many Producers, One Consumer
Clone the Sender for each producer. Drop the original sender after cloning it. Otherwise, the receiver still sees a live sender and may wait forever.
let (tx, rx) = mpsc::channel();
let mut handles = Vec::new();
for id in 0..3 {
let tx = tx.clone();
handles.push(thread::spawn(move || {
tx.send(format!("worker {id} done")).unwrap();
}));
}
drop(tx);
for message in rx {
println!("{message}");
}
for handle in handles {
handle.join().unwrap();
}Message order is determined by actual sends, not by producer creation order.
Receiving Messages
Choose a receiving method based on how the consumer should wait:
recv()blocks until a value arrives or every sender is dropped.try_recv()returns immediately. It reports whether a value is ready, the channel is empty, or the channel is disconnected.recv_timeout(duration)waits for a limited time. ItsTimeoutandDisconnectederrors distinguish an idle channel from a closed one.- Iterating over
Receiverrepeatedly callsrecv()until disconnection.
How Channels Close
A channel closes when all Sender handles are dropped. Values already queued can still be received. After the queue is empty, receiving returns Err, and iteration ends. A sender’s send returns an error if the receiver has been dropped.
Exercise
Why should the original sender be dropped after creating producer clones?
Show answer
The receiver needs every sender to be dropped before it can detect disconnection and finish its receiving loop.