Skip to content

Commit c409014

Browse files
authored
Merge pull request #1246 from Heap-Hop/opt_condvar
Update condvar in concurrency-with-threads
2 parents 2515812 + bd614f8 commit c409014

File tree

1 file changed

+7
-8
lines changed
  • src/advance/concurrency-with-threads

1 file changed

+7
-8
lines changed

src/advance/concurrency-with-threads/sync1.md

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -451,18 +451,17 @@ fn main() {
451451
let ccond = cond.clone();
452452

453453
let hdl = spawn(move || {
454-
let mut m = { *cflag.lock().unwrap() };
454+
let mut lock = cflag.lock().unwrap();
455455
let mut counter = 0;
456456

457457
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;
458+
while !*lock {
459+
// wait方法会接收一个MutexGuard<'a, T>,且它会自动地暂时释放这个锁,使其他线程可以拿到锁并进行数据更新。
460+
// 同时当前线程在此处会被阻塞,直到被其他地方notify后,它会将原本的MutexGuard<'a, T>还给我们,即重新获取到了锁,同时唤醒了此线程。
461+
lock = ccond.wait(lock).unwrap();
465462
}
463+
464+
*lock = false;
466465

467466
counter += 1;
468467
println!("inner counter: {}", counter);

0 commit comments

Comments
 (0)