Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the Best Way to Drain a mspc hannel in Rust?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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");

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading