Sub topic 7
Receiving messages: blocking, polling, and timeouts
This chapter assumes you can spawn and join threads, write move closures, and send values over an mpsc channel with send and recv. It also assumes you are comfortable with Result and pattern matching. Here you will learn the receiving side in detail: which method to call, what each one returns, and how each reports a closed channel.
The receiving methods at a glance
A Receiver<T> offers several ways to take messages out of a channel. They differ in two ways. One is whether the call waits. The other is how the call tells you "nothing arrived."
| Method | Waits? | Error type | Typical use |
|---|---|---|---|
| `recv()` | Until a message or disconnection | `RecvError` | A thread whose only job is to handle messages |
| `try_recv()` | Never | `TryRecvError::{Empty, Disconnected}` | A loop that has other work to do |
| `recv_timeout(d)` | Up to duration `d` | `RecvTimeoutError::{Timeout, Disconnected}` | Deadlines, heartbeats, watchdogs |
| `for v in rx` or `rx.iter()` | Until a message or disconnection | None, the loop just ends | Consume everything until the senders finish |
| `rx.try_iter()` | Never | None, the iterator just ends | Drain what is already queued |
Only the try_ and timeout variants can say "empty but still open." That is the distinction to watch as you read the rest of the chapter.
Blocking with recv
recv puts the calling thread to sleep until a message arrives. It returns Ok(value) for a message. It returns Err(RecvError) only when two things are both true: the queue is empty, and every Sender has been dropped.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
tx.send("hello").unwrap();
tx.send("goodbye").unwrap();
});
loop {
match rx.recv() {
Ok(msg) => println!("got {msg}"),
Err(_) => {
println!("channel closed");
break;
}
}
}
}The spawned thread owns tx. When the closure ends, tx is dropped, and the loop gets Err and stops.
Messages that were already queued are never lost when the senders go away. The receiver drains the queue first and reports the error afterward:
use std::sync::mpsc;
fn main() {
let (tx, rx) = mpsc::channel::<i32>();
tx.send(1).unwrap();
tx.send(2).unwrap();
drop(tx);
assert_eq!(rx.recv(), Ok(1));
assert_eq!(rx.recv(), Ok(2));
assert!(rx.recv().is_err());
println!("queue drained, then the error");
}Polling with try_recv
try_recv returns immediately. Its error type has two variants that mean different things:
TryRecvError::Empty: nothing is queued, but a sender is still alive, so more may come.TryRecvError::Disconnected: nothing is queued and no sender remains, so nothing will ever come.
This is the tool for a thread that must keep doing other work, such as redrawing a screen, checking a flag, or running a game loop.
use std::sync::mpsc::{self, TryRecvError};
use std::thread;
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
for i in 1..=3 {
thread::sleep(Duration::from_millis(30));
tx.send(i).unwrap();
}
});
let mut empty_polls = 0;
loop {
match rx.try_recv() {
Ok(v) => println!("got {v}"),
Err(TryRecvError::Empty) => {
empty_polls += 1;
// Stand-in for useful work.
thread::sleep(Duration::from_millis(10));
}
Err(TryRecvError::Disconnected) => break,
}
}
println!("polled an empty channel {empty_polls} times");
}The exact count of empty polls varies from run to run, because it depends on thread scheduling. The three got lines and the clean exit do not vary.
Waiting with a limit: recv_timeout
recv_timeout is a middle path. It blocks like recv, but gives up after a duration. Its error type separates the two situations that recv cannot tell apart from a timeout:
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"),
}
}This prints timed out, sender still alive, then all senders dropped. The second call returns at once, without waiting 50 ms, because a disconnected channel needs no waiting.
A deadline across several receives
The timeout applies to a single call. If you want an overall deadline for a whole loop, compute how much time remains before each call:
use std::sync::mpsc::{self, RecvTimeoutError};
use std::thread;
use std::time::{Duration, Instant};
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
for i in 0..3 {
thread::sleep(Duration::from_millis(40));
tx.send(i).unwrap();
}
// Keep the sender alive past the deadline.
thread::sleep(Duration::from_millis(500));
});
let deadline = Instant::now() + Duration::from_millis(200);
loop {
let remaining = deadline.saturating_duration_since(Instant::now());
match rx.recv_timeout(remaining) {
Ok(v) => println!("got {v}"),
Err(RecvTimeoutError::Timeout) => {
println!("deadline reached");
break;
}
Err(RecvTimeoutError::Disconnected) => {
println!("sender finished");
break;
}
}
}
}Three messages arrive at about 40, 80, and 120 ms. The sender then stays alive and quiet, so the loop ends at the 200 ms deadline with deadline reached. If you passed a fixed 200 ms to every call instead, a steady trickle of messages could keep the loop running far beyond 200 ms in total.
A timeout of Duration::ZERO makes recv_timeout behave like try_recv, except that the error type is RecvTimeoutError.
Iterating over a receiver
A Receiver implements IntoIterator, so a for loop calls a blocking recv on each pass and stops when recv would return an error. The channel from the previous chapters works this way:
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}");
}
}for value in rx consumes the receiver. Use rx.iter() when you need to keep rx afterward. Both block, and both end only when all senders are dropped.
try_iter() is the non-blocking version. It yields what is queued right now and ends at the first empty read, whether or not senders remain:
use std::sync::mpsc;
fn main() {
let (tx, rx) = mpsc::channel();
for i in 0..4 {
tx.send(i).unwrap();
}
let batch: Vec<i32> = rx.try_iter().collect();
println!("{batch:?}");
tx.send(10).unwrap();
println!("{:?}", rx.try_iter().collect::<Vec<_>>());
}This prints [0, 1, 2, 3] and then [10]. Because tx is still alive, rx.iter() here would block forever after the last value. A try_iter ending tells you only that the queue is empty. It does not tell you that the channel is closed. If you need that distinction, use try_recv and match on both error variants.
Choosing a method
Common errors
- A loop that never ends.
for v in rxhangs if anySenderis still alive. The usual cause is forgetting todropthe originaltxafter cloning it for workers. The previous chapter covers this in detail. - Treating
Timeoutas fatal.TimeoutandEmptymean the channel is still open. Retry, do other work, or check a shutdown flag. OnlyDisconnectedis permanent. - Busy-spinning on
try_recv. Add useful work or a sleep, or switch to a blocking method. - Using
try_iterto detect shutdown. It ends on an empty queue, so it cannot tell you that senders are gone. - Sharing one
Receiverbetween threads.ReceiverisSendbut notSync, so you cannot share&rxacross threads. For several consumers, wrap it inArc<Mutex<_>>, as the worker pool chapter does.
Exercise
A thread calls rx.recv_timeout(Duration::from_secs(1)) and gets Err(RecvTimeoutError::Timeout). Is it safe to stop the loop and assume the work is done? What would you check instead?
Show answer
No. Timeout means no message arrived in one second but at least one Sender is still alive, so more messages may arrive later. Only RecvTimeoutError::Disconnected means every sender is gone and the channel will never produce another value. Keep looping on Timeout, perhaps after checking a shutdown flag, and stop when you get Disconnected.
Exercise
You run let (tx, rx) = mpsc::channel::<i32>(); tx.send(5).unwrap(); let v: Vec<i32> = rx.iter().collect(); in main without dropping tx. What happens, and what are two ways to fix it?
Show answer
The program hangs. iter() blocks for a sixth read because tx is still alive, so the channel is not closed. One fix is to drop(tx) before calling rx.iter(). Another is to use rx.try_iter(), which stops at the first empty read and returns [5].