try_iter Drains Pending Without Blocking
mpsc::Receiver::try_iter drains every message already queued without ever blocking, so event loops can batch what arrived before doing work.
Code
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel::<i32>();
// producer: messages arrive over time while the consumer works
thread::spawn(move || {
for n in 1..=5 {
tx.send(n).unwrap();
thread::sleep(std::time::Duration::from_millis(1));
}
});
thread::sleep(std::time::Duration::from_millis(10));
// try_iter drains everything already pending without blocking
let drained: Vec<i32> = rx.try_iter().collect();
println!("drained now: {drained:?}");
// blocking iteration finishes after the sender drops
let rest: Vec<i32> = (&rx).into_iter().collect();
println!("rest after close: {rest:?}");
}How it works
Under the hood: the function main.
The loop for n in 1..=5 is the only repeated construct.
Caveats
- Standard-library end to end — copy it in and it runs.
Applying it
Entry signature: fn main()
Look for the drained now:, rest after close: prefixes during the file’s run; they match each line of output to the step that emitted it.
Statements that matter
let rest: Vec<i32> = (&rx).into_iter().collect();
let drained: Vec<i32> = rx.try_iter().collect();
thread::spawn(move || {
for n in 1..=5 {
tx.send(n).unwrap();
thread::sleep(std::time::Duration::from_millis(1));
}
});
Interactive Tools for This Topic
FAQ
- What does try_iter Drains Pending Without Blocking print when run?
- No setup needed: run the file and look for labeled lines like `drained now:`, `rest after close:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.