CodeBlanks Logo Icon CodeBlanks

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)

Practice 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.

Starter code

main.rs
use std::sync::mpsc::{self, TryRecvError};

fn main() {
    // buraya yaz
}

Sample solution

main.rs
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);
}

Expected output

[1, 2] Empty

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 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 Correct answer
  • Messages are lost
  • It doesn't compile
  • No downside

Explanation: try_recv is for occasionally checking inside a loop that's already running.

2 Look without waiting

Question
match rx.____() {
    Ok(m) => println!("{m}"),
    Err(_) => println!("henüz yok"),
}
Answer
match rx.try_recv() {
    Ok(m) => println!("{m}"),
    Err(_) => println!("henüz yok"),
}

Explanation: try_recv returns immediately; with no message it gives an Empty error.

3 Method and behaviour

Term Meaning
recv() Waits for a message
try_recv() Returns immediately
recv_timeout(d) Waits at most d
try_iter() Collects pending ones

All lessons in Advanced