Ad
What Is The Best Way To Drain A Mspc Channel 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:
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
Related Questions
- → Managing "this" context when creating multiple instances of objects at once based on DOM elements
- → Laravel 5.2 not working with vagrant homestead php 7
- → Exception when using Entrust middleware in Laravel 5.1
- → How to display shopify secure logo on product pages?
- → PHP Fatal error: Call to undefined method IlluminateFoundationApplication::bindShared() in ..Entrust/EntrustServiceProvider.php on line 72
- → Font Awesome Icons Weirdly Not Displaying In Shopify Store
- → Eloquent IF clause - always returns true
- → How to get basic Shopify GraphQL Admin API working with nodeJS?
- → How i can assign a role to a user during signup? ( Entrust ) ( Laravel 5.1 )
- → Laravel 5.2 with Entrust - Class name must be a valid object or a string
- → Laravel 5.2: Entrust: Call to undefined method attachPermission
- → Laravel 5.2 Entrust migrate error, cannot add foreign key constraints
- → Adding additional data fields to account information in Substrate
Ad