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 should do is just counting how many 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.
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.
CodePudding user response:
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));
}