Ad

What Is The Best Way To Drain A Mspc Channel In Rust?

- 1 answer

I need to iterate over all values that are currently stored in a receiver, and then continue with the rest of the program, which is implemented like this:

loop {
    match receiver.recv_timeout(std::time::Duration::from_nanos(0)) {
        Ok(value) => //do stuff with the value,
        _ => break
    }
}

This doesn't feel like the best / easiest way to do this. As far as I'm aware, there is no 'drain' function in the receiver struct, and the 'iter' method will cause the channel to pause the current thread if there are no more values in the receiver and wait for the next one.

Here is a example on how this is supposed to work:

use std::sync::mpsc::channel;
use std::thread::spawn;
use std::thread::sleep;


let (sender,receiver) = channel();

spawn(move || {
    for i in 0..1000 {
        sender.send(i).unwrap();
        sleep(std::time::Duration::from_nanos(10));
    }
});

sleep(std::time::Duration::from_millis(1000));

loop {
    match receiver.recv_timeout(std::time::Duration::from_nanos(0)) {
        Ok(value) => {
            println!("received {}", value);
        },
        _ => {
            break;
        },
    }
}
println!("done");
Ad

Answer

You can use try_recv and while let for a more concise and clearer loop:

while let Ok(value) = receiver.try_recv() {
    println!("received {}", value);
}
Ad
source: stackoverflow.com
Ad