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 bothSendandSynciff (if and only if)TimplementsSend.- A read-write lock counterpart:
RwLock. - Why does
lock()return aResult?- 如果持有
Mutex的執行緒發生恐慌,Mutex就會「中毒」,指出 其保護的資料可能處於不一致的狀態。如果對已中毒的互斥鎖呼叫lock(), 會發生PoisonError錯誤。無論如何,你都可以對錯誤呼叫into_inner()來復原 資料。
- 如果持有