Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust print updated value before it should update

Here’s a short code

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

fn main() {
    let num = Arc::new(Mutex::new(0u8));
    let clone = num.clone();

    thread::spawn(move || {
        loop {
            println!("{:?};", *num.lock().unwrap()); // always prints 0
            thread::sleep(Duration::from_secs(1));
            *num.lock().unwrap() = 0;
            println!("{:?};", *num.lock().unwrap()); // always prints 0
        }
    });

    listen(clone);
}

fn listen(num: Arc<Mutex<u8>>) {
    rdev::listen(move |event| {
        match event.event_type {
            rdev::EventType::KeyPress(_) => {
                *num.lock().unwrap() += 1;
            },
            _ => {},
        }
    }).unwrap();
}

All it shoud do is just counting how much times the users pressed any key on a keyboard. But this code is doesn’t work.

I added 2 println! statements – before the value is updated and after that. And I assume to get a real value in the first statement and 0 in the second one. But for some reason both println! print a zero.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Why so and how can I avoid it?


The code does work if I don’t reset value to a zero. But I have to do it.

>Solution :

It seems that you leave no time between the num read and write. So it writes the num value and immediatly read from it.

You probably want to add an extra delay statement:

loop {
    println!("{:?};", *num.lock().unwrap());
    thread::sleep(Duration::from_secs(1));
    *num.lock().unwrap() = 0;
    println!("{:?};", *num.lock().unwrap());
    //this delay will allow the other thread to modify the num before the read happens.
    thread::sleep(Duration::from_secs(1));
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading