Sub topic 5
Sending messages with channels
This chapter assumes you know ownership and move closures, and that you can spawn and join threads. It also assumes you are comfortable with Result and unwrap. Here you will send values from one thread to another.
The working model
A channel is a one-way queue with two ends. You put values in at the sending end and take them out at the receiving end, in the order they were sent. The module is called mpsc, short for "multiple producer, single consumer". This chapter uses one producer. The next chapter adds more.
mpsc::channel() returns a pair:
Sender<T>is the sending end. It has asendmethod.Receiver<T>is the receiving end. It hasrecvand other receiving methods, which a later chapter covers.
T is the type of value the channel carries. The compiler infers it from the first send. This channel is unbounded, so send never waits for space.
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 closure uses move, so tx moves into the new thread. Without move, the closure would only borrow tx. thread::spawn rejects that, because the thread might outlive main. The for loop reads from rx until the channel closes. That happens here because the thread finishes and drops tx.
Sending transfers ownership
send takes its argument by value. A String or Vec is moved into the channel, and the sender can no longer use it. This is how Rust avoids two threads touching the same data. If you still need the value, clone it before sending.
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.clone()).unwrap();
println!("producer still has {msg}");
});
println!("main received {}", rx.recv().unwrap());
}The two lines may print in either order, because the threads run independently. If you used msg after tx.send(msg) without cloning, the compiler would report a use of a moved value.
Both operations return Result
Each end can fail, because it can lose the other end.
| Call | Fails with | When |
|---|---|---|
| `tx.send(v)` | `SendError(v)` | The `Receiver` was dropped. The error hands the value back. |
| `rx.recv()` | `RecvError` | Every `Sender` was dropped and the queue is empty. |
recv blocks the calling thread until a message arrives or the channel closes. Calling unwrap on send is fine in small examples. In real code, an Err usually means the consumer has stopped, so the producer should stop too.
Common errors
- "type annotations needed". The compiler cannot infer
Tif nothing is ever sent. Writempsc::channel::<i32>(). - A receive loop that never ends. The loop only ends when every
Senderis dropped. Ifmainkeeps its owntxalive,for value in rxwaits forever. Movingtxinto the thread, as above, avoids this. The "How channels close" chapter covers the full rules. - Using the
Receiverfrom two threads.Receivercannot be cloned. There is one consumer. Sharing it needs extra machinery, which the worker pool chapter shows.
Exercise
In the first example, the spawned thread sends three values and ends. If main called rx.recv() four times instead of using a for loop, what would the first three calls and the fourth call return?
Show answer
The first three calls return Ok(0), Ok(1) and Ok(2), in that order. The fourth returns Err(RecvError). The thread has finished, so its Sender was dropped and the queue is empty.