Merge pull request #1246 from Heap-Hop/opt_condvar

Update condvar in concurrency-with-threads
pull/1293/head
Sunface 1 year ago committed by GitHub
commit c4090146a7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -451,18 +451,17 @@ fn main() {
let ccond = cond.clone(); let ccond = cond.clone();
let hdl = spawn(move || { let hdl = spawn(move || {
let mut m = { *cflag.lock().unwrap() }; let mut lock = cflag.lock().unwrap();
let mut counter = 0; let mut counter = 0;
while counter < 3 { while counter < 3 {
while !m { while !*lock {
m = *ccond.wait(cflag.lock().unwrap()).unwrap(); // wait方法会接收一个MutexGuard<'a, T>,且它会自动地暂时释放这个锁,使其他线程可以拿到锁并进行数据更新。
} // 同时当前线程在此处会被阻塞直到被其他地方notify后它会将原本的MutexGuard<'a, T>还给我们,即重新获取到了锁,同时唤醒了此线程。
lock = ccond.wait(lock).unwrap();
{
m = false;
*cflag.lock().unwrap() = false;
} }
*lock = false;
counter += 1; counter += 1;
println!("inner counter: {}", counter); println!("inner counter: {}", counter);

Loading…
Cancel
Save