From 46675a1db8fa524c1f5708ef31e55652cbc3fb69 Mon Sep 17 00:00:00 2001 From: csf Date: Thu, 6 Jul 2023 22:09:59 +0900 Subject: [PATCH 1/2] update condvar --- src/advance/concurrency-with-threads/sync1.md | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/src/advance/concurrency-with-threads/sync1.md b/src/advance/concurrency-with-threads/sync1.md index a37ac58a..b54380b5 100644 --- a/src/advance/concurrency-with-threads/sync1.md +++ b/src/advance/concurrency-with-threads/sync1.md @@ -456,18 +456,15 @@ 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 { + lock = ccond.wait(lock).unwrap(); } + + *lock = false; counter += 1; println!("inner counter: {}", counter); From bd614f8944237469c64d19dc5a9791ee7810aa23 Mon Sep 17 00:00:00 2001 From: csf Date: Wed, 12 Jul 2023 17:37:20 +0900 Subject: [PATCH 2/2] add a comment to mothed wait() --- src/advance/concurrency-with-threads/sync1.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/advance/concurrency-with-threads/sync1.md b/src/advance/concurrency-with-threads/sync1.md index b54380b5..88e71af1 100644 --- a/src/advance/concurrency-with-threads/sync1.md +++ b/src/advance/concurrency-with-threads/sync1.md @@ -461,6 +461,8 @@ fn main() { while counter < 3 { while !*lock { + // wait方法会接收一个MutexGuard<'a, T>,且它会自动地暂时释放这个锁,使其他线程可以拿到锁并进行数据更新。 + // 同时当前线程在此处会被阻塞,直到被其他地方notify后,它会将原本的MutexGuard<'a, T>还给我们,即重新获取到了锁,同时唤醒了此线程。 lock = ccond.wait(lock).unwrap(); }