Channels
In the previous lesson a thread handed back its result through join, and only once it had finished all its work. What if a worker wants to pass finished parts along one at a time, without waiting for the end of the shift?
A workshop has a pneumatic tube for that: a pipe between benches. One worker puts a capsule into the tube at his desk, and another takes it out at the other end. Capsules arrive in the order they were sent. Such a pipe between threads is called a channel.
The picture is off in one respect. With a real pneumatic tube you can send a capsule and keep a copy. A value sent into a channel is moved: the sender no longer has it.
A channel and its two ends
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let msg = String::from("hello");
tx.send(msg).unwrap();
});
let got = rx.recv().unwrap();
println!("{got}"); // hello
}Let's go through the example line by line:
mpsc::channel()creates a channel and returns a tuple of its two ends. We split it right away intotx, the sender, andrx, the receiver.movemovestxinto the new thread: now that thread can send.tx.send(msg)moves the string into the channel. The method returns aResult: it fails if the receiver is already gone.rx.recv()waits until a message shows up in the channel and returns aResultholding it.mainprintshello.
There is no need for join here: recv itself waits until the thread sends the string.
The letters mpsc stand for "multiple producer, single consumer": a channel can have any number of senders but only one receiver.
Looping over the receiver
You can walk over the receiver with a for loop. Each step of the loop waits for the next message. This example has no use at all: a function's path can be written in full, std::sync::mpsc::channel() and std::thread::spawn. It means the same thing; use only shortens the code.
fn main() {
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
for word in ["one", "two", "three"] {
tx.send(word).unwrap();
}
});
let mut got = Vec::new();
for word in rx {
got.push(word);
}
println!("{got:?}"); // ["one", "two", "three"]
}What happens here:
- The thread sends three words in order.
for word in rxtakes the messages in the order they were sent: the channel works as a queue.- After sending the third word, the thread ends, and
txis dropped with it. - The loop sees that no senders are left and ends.
mainprints["one", "two", "three"].
The rule for the end of the loop is worth remembering: a for over a receiver ends when ALL senders have been dropped. While even one is alive, the loop waits for the next message.
Several senders
A sender can be cloned: tx.clone() gives one more entrance into the same tube. Each worker gets its own clone, and the messages from all of them arrive at one receiver.
use std::sync::mpsc;
fn main() {
let (tx, rx) = mpsc::channel();
for id in 1..=3 {
let tx = tx.clone();
std::thread::spawn(move || tx.send(id * 10).unwrap());
}
drop(tx);
let mut total = 0;
for n in rx {
total += n;
}
println!("{total}"); // 60
}Let's see what is new here:
- on each step of the loop
let tx = tx.clone();shadows the name: the clone goes into the thread, and the originaltxstays inmain; - the operating system decides in which order
10,20and30arrive, so the example adds the numbers instead of printing them; drop(tx)drops the original sender inmain, and the loop ends when all three threads have finished.
Order is guaranteed only for the messages of one sender. Interviewers like to ask about this: "In what order do messages come out of a channel?"
Common mistake
The clones went to the threads, and the original sender stayed in main:
use std::sync::mpsc;
fn main() {
let (tx, rx) = mpsc::channel();
for id in 1..=3 {
let tx = tx.clone();
std::thread::spawn(move || tx.send(id * 10).unwrap());
}
let mut total = 0;
for n in rx { // ✗
total += n;
}
println!("{total}");
}The program compiles, but it hangs and prints nothing. All three messages arrived and the threads ended, but the tx in main is still alive. The channel is open, and the loop waits forever for a fourth message. The fix is drop(tx) before the loop, as in the example above.
Key points
mpsc::channel()returns a pair(tx, rx);sendmoves a value into the channel, andrecvwaits for a message.- Messages from one sender arrive in the order they were sent.
for x in rxwaits for each message and ends when every sender has been dropped; it needs nojoin.tx.clone()gives one more sender; the originaltxleft inmainkeeps the channel open.