diff --git a/src/advance/concurrency-with-threads/sync1.md b/src/advance/concurrency-with-threads/sync1.md index 93f59abe..5912e6c3 100644 --- a/src/advance/concurrency-with-threads/sync1.md +++ b/src/advance/concurrency-with-threads/sync1.md @@ -451,18 +451,17 @@ fn main() { let ccond = cond.clone(); let hdl = spawn(move || { - let mut m = { *cflag.lock().unwrap() }; + let mut lock = cflag.lock().unwrap(); let mut counter = 0; while counter < 3 { - while !m { - m = *ccond.wait(cflag.lock().unwrap()).unwrap(); - } - - { - m = false; - *cflag.lock().unwrap() = false; + while !*lock { + // wait方法会接收一个MutexGuard<'a, T>,且它会自动地暂时释放这个锁,使其他线程可以拿到锁并进行数据更新。 + // 同时当前线程在此处会被阻塞,直到被其他地方notify后,它会将原本的MutexGuard<'a, T>还给我们,即重新获取到了锁,同时唤醒了此线程。 + lock = ccond.wait(lock).unwrap(); } + + *lock = false; counter += 1; println!("inner counter: {}", counter);