DEV Community

loading...

Using Mutex instead of Channel in Rust

Vee Satayamas
Free software developer
・1 min read

(2019-06-02)

When the producer sends messages too frequently, and the producer takes too much time to process each message. I wrote a code for

I want to discard aging messages and process only the latest one. So I wrote a code for repeating receive messages until the channel is empty for a short duration. However, I found my code was too complicated. So I use shared memory with mutex-lock for inter-thread communication instead of a channel.

use std::sync::{Mutex, Arc};
use std::{thread, time};
use std::collections::HashMap;

fn main() {
    let r_shared_data = Arc::new(Mutex::new(None));
    let w_shared_data = r_shared_data.clone();

    thread::spawn(move || {
        let tx_delay_time = time::Duration::from_millis(100);
        loop {
            for i in 1..1000 {
                let mut h = HashMap::new();
                h.insert("X", i);
                let mut w = w_shared_data.lock().unwrap();
                *w = Some(h);
                if i % 10 == 0 {
                   thread::sleep(tx_delay_time);
                }                
            }
        }
    });

    let task_proc_time = time::Duration::from_millis(500);
    loop {
         let r = r_shared_data.lock().unwrap();
        dbg!(r);
        // long task
        thread::sleep(task_proc_time);
    }
}

Enter fullscreen mode Exit fullscreen mode


`

Discussion (0)