繁体   English   中英

在更新之前打印更新的值

[英]Print updated value before it should update

这是一个简短的代码

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语句 - 在值更新之前和之后。 我假设在第一个语句中得到一个真正的值,在第二个语句中得到0 但由于某种原因,两个println都打印一个零。

为什么会这样,我该如何避免呢?


如果我不将值重置为零,则代码确实有效。 但我必须这样做。

似乎您在num读取和写入之间没有时间。 所以它写入num值并立即从中读取。

您可能想要添加一个额外的延迟语句:

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM