DEV Community

Vee Satayamas
Vee Satayamas

Posted on

Using Mutex instead of Channel in Rust


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 {

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

Enter fullscreen mode Exit fullscreen mode


Oldest comments (0)