Skip to content

Commit 3c57ef4

Browse files
authored
bug: dead lock in condvar example (#6)
1 parent 1b252f6 commit 3c57ef4

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

33_concurrency/examples/condvar.rs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,13 @@ fn main() {
99

1010
thread::spawn(move || {
1111
let (lock, cvar) = &*pair2;
12-
let mut started = lock.lock().unwrap();
13-
*started = true;
12+
13+
// 通过离开作用域来释放锁,否则主线程会一直阻塞在获取锁上
14+
{
15+
let mut started = lock.lock().unwrap();
16+
*started = true;
17+
}
18+
1419
eprintln!("I'm a happy worker!");
1520
// 通知主线程
1621
cvar.notify_one();
@@ -27,4 +32,7 @@ fn main() {
2732
started = cvar.wait(started).unwrap();
2833
}
2934
eprintln!("Worker started!");
35+
36+
// 等待 worker 线程
37+
thread::sleep(Duration::from_secs(3600));
3038
}

0 commit comments

Comments
 (0)