Sub topic 7
Receiving messages: blocking, polling, and timeouts
This chapter assumes you can spawn threads, use move closures, and create an mpsc channel with Sender and Receiver. You should also be comfortable with Result and match. Here you will pick the right way to read from a Receiver.
Four ways to receive
A Receiver<T> offers four common ways to get values. They differ in how long they wait and what errors they return.
| Method | Waits? | Returns | Error cases |
|---|---|---|---|
| `recv()` | Until a value arrives or all senders drop | `Result<T, RecvError>` | `RecvError` (disconnected) |
| `try_recv()` | Never | `Result<T, TryRecvError>` | `Empty`, `Disconnected` |
| `recv_timeout(d)` | Up to duration `d` | `Result<T, RecvTimeoutError>` | `Timeout`, `Disconnected` |
| `for v in rx` / `rx.iter()` | Blocks on each item | Yields `T` until closed | None, the loop just ends |
Blocking with recv and iteration
recv blocks the calling thread until a message arrives. It returns Err only when the channel is empty and every Sender has been dropped. No more messages can ever come, so the error means "done".
The iterator form wraps recv in a loop. It stops when recv would return Err. This is the usual choice for a consumer that processes everything until the producers finish.
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 loop ends on its own because tx is dropped when the spawned thread finishes.
Polling with try_recv
try_recv returns immediately. Use it when the thread has other work to do and should only check for messages now and then, for example a loop that redraws a screen or does a unit of computation between checks.
It has two distinct failures. Empty means no message is ready but a sender is still alive. Disconnected means the channel is empty and closed. Treat them differently: keep working on Empty, stop on Disconnected.
A common mistake is calling try_recv in a tight loop with nothing else to do. That burns a CPU core while it spins. If you have no other work, use recv or recv_timeout instead.
Waiting a limited time with recv_timeout
recv_timeout is the middle ground. It blocks, but only for a set duration. This lets a thread wake up periodically to check a shutdown flag, log a heartbeat, or give up on a slow producer.
use std::sync::mpsc::{self, RecvTimeoutError};
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::channel::<i32>();
match rx.recv_timeout(Duration::from_millis(50)) {
Ok(v) => println!("got {v}"),
Err(RecvTimeoutError::Timeout) => println!("timed out, sender still alive"),
Err(RecvTimeoutError::Disconnected) => println!("all senders dropped"),
}
drop(tx);
match rx.recv_timeout(Duration::from_millis(50)) {
Ok(v) => println!("got {v}"),
Err(RecvTimeoutError::Timeout) => println!("timed out, sender still alive"),
Err(RecvTimeoutError::Disconnected) => println!("all senders dropped"),
}
}The first call times out because tx is still alive but nothing was sent. After drop(tx), the second call reports Disconnected right away, without waiting the full 50 ms.
Choosing a method
Common errors
- Treating
Emptyas a failure. It is a normal state, not an error to propagate. - Looping on
recv_timeoutand ignoringDisconnected. The loop then never ends, because every later call returnsDisconnectedimmediately and you spin. - Holding a
Senderin the consuming thread and then usingfor v in rx. The loop never ends because one sender is still alive. Drop it first.
Exercise
A worker loops on rx.try_recv(), does nothing on Err(TryRecvError::Empty), and breaks on Disconnected. It uses 100% of a CPU core. What is wrong, and what would you change if the worker has no other work to do?
Show answer
With no other work, the loop spins and repeatedly polls an empty channel. Replace it with a blocking for msg in rx loop (or recv), which sleeps until a message arrives and ends when all senders drop. If the worker also needs to wake periodically, use recv_timeout.
Exercise
What does recv_timeout return if the channel is empty and every Sender has been dropped, and does it wait for the full timeout?
Show answer
It returns Err(RecvTimeoutError::Disconnected) and does not wait for the full timeout, because the disconnection is detected immediately.