sunface / rust-course

“连续八年成为全世界最受喜爱的语言,无 GC 也无需手动内存管理、极高的性能和安全性、过程/OO/函数式编程、优秀的包管理、JS 未来基石" — 工作之余的第二语言来试试 Rust 吧。本书拥有全面且深入的讲解、生动贴切的示例、德芙般丝滑的内容,这可能是目前最用心的 Rust 中文学习教程 / Book
https://course.rs
24.92k stars 2.15k forks source link

Update condvar in concurrency-with-threads #1246

Closed Heap-Hop closed 12 months ago

sunface commented 1 year ago

兄弟能否给一下修改的上下文和理由 :D

Heap-Hop commented 1 year ago

Hello, 抱歉上次提交时没有详细说明。

原来例子中,在新线程的代码块中会出现多次获取和释放锁,这个应该是没必要操作。且可能无法让读者真正理解wait方法的作用。

参考官方文档中Condvar的用例 https://doc.rust-lang.org/stable/std/sync/struct.Condvar.html

// Wait for the thread to start up.
let (lock, cvar) = &*pair;
let mut started = lock.lock().unwrap();
while !*started {
    started = cvar.wait(started).unwrap();
}

以及对于wait方法的说明 https://doc.rust-lang.org/stable/std/sync/struct.Condvar.html#method.wait

This function will atomically unlock the mutex specified (represented by guard) and block the current thread. This means that any calls to notify_one or notify_all which happen logically after the mutex is unlocked are candidates to wake this thread up. When this function call returns, the lock specified will have been re-acquired.

调用wait()时传入guard进去会自动暂时“释放”锁,直到notify后会重新返回guard。

所以我参照官方用例尝试进行了一些修改调整。