DEV Community

Vee Satayamas
Vee Satayamas

Posted on

2 2

Avoiding old data in Rust channel

(2019-06-02)

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;
    }
}
Enter fullscreen mode Exit fullscreen mode


`

I feel that the program look too complicated. Perhaps I shouldn't a channel at all in this case. 🤣

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs