Avoiding old data in Rust channel
Sometimes a consumer takes a long time to finish a task, and producers keep sending data. This situation can cause a memory leak. Keep processing out-dated data makes no sense in some applications.
So I write a program to keep receiving data within 10ms time frame, and discard old data.
use std::sync::mpsc::channel;
use std::{thread, time};
fn main() {
let (tx, rx) = channel();
thread::spawn(move || {
let tx_delay_time = time::Duration::from_millis(100);
loop {
for i in 1..1000 {
tx.send(i).expect("Cannot send");
if i % 10 == 0 {
thread::sleep(tx_delay_time);
}
}
}
});
let timeout = time::Duration::from_millis(10);
loop {
println!("LOOP");
let mut i = None;
loop {
match rx.recv_timeout(timeout) {
Ok(j) => {
i = Some(j);
},
Err(_) => {
if i.is_some() {
break;
}
}
}
}
// long task ...
println!("{:?}", i);
i = None;
}
}
I feel that the program look too complicated. Perhaps I shouldn't a channel at all in this case. 🤣