Sub topic 11
Bounded channels and backpressure
This chapter assumes you know how to spawn and join threads, move values into closures, and use mpsc::channel with Sender and Receiver. It also assumes you know how a channel closes when all senders are dropped.
The problem with unbounded channels
mpsc::channel is unbounded. send never blocks, and the channel's internal buffer grows as needed. If a producer is faster than its consumer, messages pile up in memory. Nothing in the program warns you. The only symptom is steadily growing memory use, which can end in an out-of-memory crash.
Backpressure fixes this. It means a slow consumer pushes back on a fast producer, so the producer slows down instead of piling up work.
sync_channel
mpsc::sync_channel(n) creates a bounded channel that holds at most n messages. It returns a SyncSender<T> and a normal Receiver<T>.
- While the buffer has room,
sendreturns right away. - When the buffer is full,
sendblocks until the receiver takes a message. SyncSendercan be cloned, likeSender.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::sync_channel::<u32>(2);
let producer = thread::spawn(move || {
for i in 0..5 {
tx.send(i).unwrap();
}
});
let got: Vec<u32> = rx.iter().collect();
producer.join().unwrap();
assert_eq!(got, vec![0, 1, 2, 3, 4]);
println!("{got:?}");
}The producer can queue two messages and then waits. Each time the consumer takes one, the producer sends another. When the producer finishes, tx is dropped, the channel closes, and rx.iter() ends. The output is [0, 1, 2, 3, 4].
Choosing the capacity
The capacity sets how much slack the producer gets before it must wait.
| Capacity | Behavior |
|---|---|
| Larger than 1 | A buffer absorbs bursts. Memory use is capped at `n` messages. |
| 1 | At most one message waits in the buffer. |
| 0 | A rendezvous channel. `send` blocks until a receiver is ready to take the value. |
Pick the smallest capacity that keeps the consumer busy. A very large capacity brings back the memory problem you were trying to avoid.
Sending without blocking
Blocking is sometimes the wrong choice. SyncSender::try_send returns immediately and reports why it failed:
TrySendError::Full(value)means the buffer is full. You get the value back and can drop it, retry later, or report the overload.TrySendError::Disconnected(value)means the receiver is gone.
use std::sync::mpsc::{self, TrySendError};
fn main() {
let (tx, rx) = mpsc::sync_channel::<u32>(1);
tx.try_send(1).unwrap();
match tx.try_send(2) {
Ok(()) => println!("queued 2"),
Err(TrySendError::Full(v)) => println!("full, dropped {v}"),
Err(TrySendError::Disconnected(v)) => println!("receiver gone, lost {v}"),
}
println!("received {}", rx.recv().unwrap());
}This prints full, dropped 2 and then received 1. Dropping messages under load is called load shedding. It suits data where only recent values matter, such as sensor readings.
Common errors
- Deadlock with capacity 0 or a full buffer. If one thread both sends and receives on the same channel, and sends first into a full channel, it waits for itself. Send and receive from different threads.
- Sending before the consumer exists. With capacity 0, a
sendin the main thread blocks forever if the consumer thread has not been started yet. Spawn the consumer first. - Forgetting to drop extra senders. As with
channel, the receiving loop ends only after everySyncSenderclone is dropped. - A dropped receiver.
sendreturnsErr(SendError(value)). A producer blocked on a full buffer is woken with that error when the receiver is dropped, so it does not hang.
Exercise
A producer sends 1,000,000 messages into a sync_channel(10). The consumer is slow. What happens to the producer, and what is the most memory the channel can hold at any time?
Show answer
The producer blocks in send whenever 10 messages are already waiting, and it continues each time the consumer receives one. The channel holds at most 10 messages, so memory stays bounded. With an unbounded channel, up to about 1,000,000 messages could be queued.
Exercise
You are reading sensor values and only the newest ones matter. Which method on SyncSender lets the producer avoid blocking, and which error variant tells it the buffer was full?
Show answer
Use try_send. It returns Err(TrySendError::Full(value)) when the buffer is full, and the producer can drop that value and move on.