官方文档关于条件变量Condvar的代码直接给我看懵了
use std::sync::{Arc, Mutex, Condvar};
use std::thread;
let pair = Arc::new((Mutex::new(false), Condvar::new()));
let pair2 = Arc::clone(&pair);
thread::spawn(move|| {
let (lock, cvar) = &*pair2;
let mut started = lock.lock().unwrap();
*started = true;
// We notify the condvar that the value has changed.
cvar.notify_one();
});
// Wait for the thread to start up.
let (lock, cvar) = &*pair;
let mut started = lock.lock().unwrap();
// As long as the value inside the `Mutex<bool>` is `false`, we wait.
while !*started {
started = cvar.wait(started).unwrap();
}
瞬间冒出好几个疑问
- 这段代码啥意思?
- 为什么条件变量里面还有锁?
wait()
操作被通知后发生了什么?
仔细理解了一下才明白,原来条件变量可能会通过notify_all()
方法通知多个等待线程,那么当它们同时访问资源时就会有竞争冲突,为了避免这一情况,资源要通过互斥锁来保护,所以变成了条件变量(互斥锁(资源))
。
上面代码的逻辑大概这样
通知线程:
1. 获取互斥锁
2. 修改资源
3. 条件变量notify_one通知等待线程
等待线程:
1. 获取互斥锁
2. 判断条件,不符合直接结束
3. 符合的话,调用条件变量condvar.wait()方法等待通知,并同时释放锁
4. 收到通知,再次尝试获取互斥锁
5. 获取到之后,继续回到第2步
假设通知线程先执行,那么等待线程会直接跳过wait()
,因为不符合等待的条件;而如果等待线程先执行,会在阻塞在第3步中,同时会释放锁,让通知线程有机会能获取到锁,从而发送通知。
这里的逻辑有些奇怪的地方,比如为什么要先获取互斥锁、调用wait()
释放锁、被通知后再次获取锁,而不是直接wait()
等待、被通知后获取锁,这样实现的原因是为了避免通知的时候某些等待线程正在尝试wait()
,但刚好错过了通知,于是永远的等待,虽然刚开始较难理解,但确实从安全的角度上看很合理。
为了更好理解多个等待线程的情况,让chatgpt帮忙写了个例子
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
fn main() {
let pair = Arc::new((Mutex::new(0), Condvar::new()));
let mut handels = vec![];
for i in 0..5 {
let tmp_pair = Arc::clone(&pair);
handels.push(thread::spawn(move || {
let (lock, cvar) = &*tmp_pair;
let mut started = lock.lock().unwrap();
while *started == 0 {
started = cvar.wait(started).unwrap();
*started += 1;
println!("线程{i}: {}", started);
}
}))
}
let pair_clone = pair.clone();
thread::spawn(move || {
let (lock, cvar) = &*pair_clone;
let mut num = lock.lock().unwrap();
// 改变条件
*num = 100;
// 通知所有等待的线程
cvar.notify_all();
});
for handle in handels {
handle.join().unwrap();
}
}