[英]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 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.我添加了 2 个
println
语句 - 在值更新之前和之后。 And I assume to get a real value in the first statement and 0
in the second one.我假设在第一个语句中得到一个真正的值,在第二个语句中得到
0
。 But for some reason both println
print a zero.但由于某种原因,两个
println
都打印一个零。
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.
但我必须这样做。
It seems that you leave no time between the num
read and write.似乎您在
num
读取和写入之间没有时间。 So it writes the num
value and immediatly read from it.所以它写入
num
值并立即从中读取。
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)) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.