打印更新值之前应更新
这是一个简短的代码,
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();
}
它应该做的只是计算用户按键盘上的任何键的次数。但是此代码行不通。
我添加了2 println!
语句 - 在更新该值之前。我假设在第一个语句中获得了一个实际值,第二个语句在第二个语句中获得了一个。但是由于某种原因,println!
打印一个零。
为什么这么做,如何避免它?
如果我不将值重置为零,则该代码确实可以工作。但是我必须这样做。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看来您在
num
读写之间没有时间。因此,它写入num
值并立即从中读取。您可能想添加一个额外的延迟语句:
It seems that you leave no time between the
num
read and write. So it writes thenum
value and immediatly read from it.You probably want to add an extra delay statement: