Sub topic 5
Sending messages with channels
This chapter covers the basic channel API in std::sync::mpsc. It assumes you can spawn and join threads, that you know why thread closures use move, and that you have met the Send trait. It also assumes you are comfortable with Result, unwrap, generics, and running programs with cargo.
Why channels
Threads need a way to pass results and work to each other. Rust offers two main approaches. One is shared memory guarded by a lock, covered later in this tutorial. The other is message passing: one thread sends a value, and another thread receives it. The idea is often summed up as "do not communicate by sharing memory; share memory by communicating."
The standard library provides message passing in the std::sync::mpsc module. The name stands for multiple producer, single consumer. Many threads may send into a channel, but only one thread receives from it. This chapter focuses on the simplest case, one sender and one receiver. The next chapter adds more senders.
Creating a channel
mpsc::channel() creates a channel and returns a tuple of two endpoints.
Sender<T>is the sending end. Itssendmethod puts a value of typeTinto the channel.Receiver<T>is the receiving end. Itsrecvmethod takes a value out.
Both endpoints share the same message type T. You can write it explicitly with mpsc::channel::<String>(), or let the compiler infer it from the first send.
Internally, the channel is a queue. Values come out in the order they went in (first in, first out). This version of the channel has no size limit, so send never waits for space. The bounded alternative, sync_channel, has its own chapter.
A first example
The sender moves into a spawned thread. The main thread keeps the receiver.
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}");
}
}This prints got 0, got 1, and got 2, then the program ends. Three details matter here.
txis moved into the closure withmove. The spawned thread now owns the onlySender.for value in rxcallsrecvrepeatedly. It blocks while the channel is empty.- The loop stops by itself. When the spawned thread finishes,
txis dropped. A channel with no senders left is closed, and the receiver then reports that nothing more will arrive. The chapter "How channels close" covers this in full.
Sending transfers ownership
send takes its argument by value. For types that are not Copy, such as String or Vec, the sending thread gives the value away. The compiler enforces this, so the sender cannot touch the value after sending it.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let msg = String::from("hello from the worker");
tx.send(msg).unwrap();
// println!("{msg}"); // error[E0382]: borrow of moved value: `msg`
});
let received = rx.recv().unwrap();
println!("got: {received}");
}If the commented line were active, the program would not compile. This is how channels prevent data races. At any moment exactly one thread owns the value, so no two threads can access it at once. No lock is needed, because ownership itself provides the exclusion.
Moving a String copies only its pointer, length, and capacity. The heap buffer stays where it is, so sending large values is cheap.
The message type must be Send, which is the trait from the previous chapter. Types such as Rc<T> are not Send, so mpsc::channel::<Rc<i32>>() can be created, but sending it to another thread fails to compile once you move an endpoint into thread::spawn.
What send and recv return
Both operations can fail, and both report failure through Result.
| Call | Success | Failure | Cause of failure |
|---|---|---|---|
| `tx.send(value)` | `Ok(())` | `Err(SendError<T>)` | The `Receiver` was dropped |
| `rx.recv()` | `Ok(value)` | `Err(RecvError)` | The channel is empty and every `Sender` was dropped |
recv blocks the calling thread until a message arrives or the channel closes. A blocked thread uses no CPU time, so a consumer can wait on recv without spinning.
send on this channel type never blocks. It fails only if no receiver exists. Because the message could not be delivered, SendError<T> hands the value back to you in its public field .0:
use std::sync::mpsc;
fn main() {
let (tx, rx) = mpsc::channel::<String>();
drop(rx);
match tx.send(String::from("lost")) {
Ok(()) => println!("sent"),
Err(e) => println!("receiver gone, value returned: {}", e.0),
}
}This prints receiver gone, value returned: lost. You can retry, log the value, or send it elsewhere.
Should you call unwrap?
Examples in this tutorial often write tx.send(x).unwrap(). That means "if the receiver has vanished, panic." It is reasonable in short programs, where a missing receiver signals a bug. In long-running code, a missing receiver is often a normal shutdown signal. A worker may then prefer to stop quietly:
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel::<u32>();
let producer = thread::spawn(move || {
for i in 0..1000 {
if tx.send(i).is_err() {
println!("consumer gone, stopping at {i}");
return;
}
}
});
let first = rx.recv().unwrap();
println!("first = {first}");
drop(rx);
producer.join().unwrap();
}The exact stopping point varies from run to run, because the producer races with the drop. It may also finish all 1000 sends before the receiver is dropped. Both outcomes are correct.
Sending different kinds of messages
A channel carries one type, but that type can be an enum. This lets one channel carry several kinds of messages, including a shutdown request.
use std::sync::mpsc;
use std::thread;
enum Message {
Text(String),
Number(i64),
Quit,
}
fn main() {
let (tx, rx) = mpsc::channel();
let worker = thread::spawn(move || loop {
match rx.recv() {
Ok(Message::Text(s)) => println!("text: {s}"),
Ok(Message::Number(n)) => println!("number: {}", n * 2),
Ok(Message::Quit) | Err(_) => {
println!("worker stopping");
break;
}
}
});
tx.send(Message::Text(String::from("start"))).unwrap();
tx.send(Message::Number(21)).unwrap();
tx.send(Message::Quit).unwrap();
worker.join().unwrap();
}The output is always text: start, number: 42, worker stopping, in that order. A single sender's messages arrive in the order they were sent. Matching on Err(_) as well as Quit means the worker also stops if the sender is dropped without a Quit.
Common errors
- Using a value after sending it. The compiler reports
borrow of moved value. Clone the value before sending if you still need a copy. - Forgetting
move. Without it, the closure borrowstxfrommain, andthread::spawnrejects the borrow because the thread might outlive it. - Trying to clone the
Receiver.Receiverdoes not implementClone, because the design allows a single consumer. To spread work over several threads, you need a different pattern, which the worker pool chapter shows. - A receive loop that never ends. If any
Senderstays alive,recvandfor value in rxwait forever. A common cause is keeping the originaltxinmainwhile a thread uses a clone. The next chapter explains this case. - Inferring the type too late.
mpsc::channel()with nosendcall anywhere gives the errortype annotations needed. Writechannel::<T>().
Exercise
A producer thread calls tx.send(report) where report is a Vec<String>, and the next line prints report.len(). The code does not compile. Why, and what are two ways to fix it?
Show answer
send takes the value by value, so report moves into the channel and the thread can no longer use it (error E0382, borrow of moved value). One fix is to read what you need before sending, for example let n = report.len(); and then print n after the send. The other is to send a clone with tx.send(report.clone()), which costs an extra copy of the data.
Exercise
You create let (tx, rx) = mpsc::channel::<i32>(); and then call drop(rx);. What does tx.send(5) return, and how do you get the 5 back?
Show answer
It returns Err(SendError(5)), because no receiver exists to take the message. The unsent value is stored in the error's public field, so match tx.send(5) { Err(e) => e.0, .. } gives you the 5.