Rust
try_recv
Read without blocking using try_recv.
try_recv
recv waits until a message arrives. try_recv looks without waiting and returns immediately. It's used in code that must not stop, like a game loop or a UI thread:
use std::sync::mpsc::TryRecvError;
loop {
match rx.try_recv() {
Ok(m) => isle(m),
Err(TryRecvError::Empty) => break, // no message for now
Err(TryRecvError::Disconnected) => return, // the sender closed
}
}
Separating the two error kinds matters: Empty is temporary, Disconnected is permanent.
Draining the queue
try_iter can also be used to collect the messages piled up in the channel without waiting; it yields those present at the moment and ends:
tx.send(1).unwrap();
tx.send(2).unwrap();
let bekleyenler: Vec<i32> = rx.try_iter().collect(); // [1, 2]
println!("{:?}", rx.try_recv()); // Err(Empty)
Exercise Take the pending ones
Send 1 and 2 to a channel. Collect the messages into a vector with try_recv until Empty comes. Print the vector and the final error ({:?}) separated by a space.
Show example solution
use std::sync::mpsc::{self, TryRecvError};
fn main() {
let (tx, rx) = mpsc::channel();
tx.send(1).unwrap();
tx.send(2).unwrap();
let mut alinan = Vec::new();
let son = loop {
match rx.try_recv() {
Ok(m) => alinan.push(m),
Err(e) => break e,
}
};
println!("{:?} {:?}", alinan, son);
assert_eq!(son, TryRecvError::Empty);
}
Test yourself
-
What is the downside of calling <code>try_recv</code> continuously in an empty loop?
- It burns CPU for nothing (busy waiting); recv or recv_timeout fits better
- Messages are lost
- It doesn't compile
- No downside
Show answer
It burns CPU for nothing (busy waiting); recv or recv_timeout fits better — try_recv is for occasionally checking inside a loop that's already running.
-
Look without waiting
match rx.____() {
Ok(m) => println!("{m}"),
Err(_) => println!("henüz yok"),
}
Show answer
match rx.try_recv() {
Ok(m) => println!("{m}"),
Err(_) => println!("henüz yok"),
}
-
Method and behaviour
- recv()
- Waits for a message
- try_recv()
- Returns immediately
- recv_timeout(d)
- Waits at most d
- try_iter()
- Collects pending ones
Next lesson: tokio::sync::mpsc