互斥器(Mutex)
Mutex<T> ensures mutual exclusion and allows mutable access to T behind a read-only interface (another form of interior mutability):
use std::sync::Mutex; fn main() { let v = Mutex::new(vec![10, 20, 30]); println!("v: {:?}", v.lock().unwrap()); { let mut guard = v.lock().unwrap(); guard.push(40); } println!("v: {:?}", v.lock().unwrap()); }
请注意我们如何设置 impl<T: Send> Sync for Mutex<T> 通用 实现。
- Mutexin Rust looks like a collection with just one element --- the protected data.- 在访问受保护的数据之前不可能忘记获取互斥量。
 
- 你可以通过获取锁,从 &Mutex<T>中获取&mut T。MutexGuard能够确保&mut T存在的时间不会比持有锁的时间更长。
- Mutex<T>implements both- Sendand- Synciff (if and only if)- Timplements- Send.
- A read-write lock counterpart: RwLock.
- Why does lock()return aResult?- 如果持有 Mutex的线程发生panic,Mutex便会“中毒”并发出信号, 表明其所保护的数据可能处于不一致状态。对中毒的互斥量调用lock()将会失败, 并将显示PoisonError。无论如何,你可以对该错误调用into_inner()来 恢复数据。
 
- 如果持有