We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
2 parents 2515812 + bd614f8 commit c409014Copy full SHA for c409014
src/advance/concurrency-with-threads/sync1.md
@@ -451,18 +451,17 @@ fn main() {
451
let ccond = cond.clone();
452
453
let hdl = spawn(move || {
454
- let mut m = { *cflag.lock().unwrap() };
+ let mut lock = cflag.lock().unwrap();
455
let mut counter = 0;
456
457
while counter < 3 {
458
- while !m {
459
- m = *ccond.wait(cflag.lock().unwrap()).unwrap();
460
- }
461
-
462
- {
463
- m = false;
464
- *cflag.lock().unwrap() = false;
+ while !*lock {
+ // wait方法会接收一个MutexGuard<'a, T>,且它会自动地暂时释放这个锁,使其他线程可以拿到锁并进行数据更新。
+ // 同时当前线程在此处会被阻塞,直到被其他地方notify后,它会将原本的MutexGuard<'a, T>还给我们,即重新获取到了锁,同时唤醒了此线程。
+ lock = ccond.wait(lock).unwrap();
465
}
+
+ *lock = false;
466
467
counter += 1;
468
println!("inner counter: {}", counter);
0 commit comments