mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-03-29 17:10:46 +02:00
Example contained unnecessary explicit type info for the vector in Mutex v. Rust will magically do the needful conversions for us. Code looks cleaner/simpler without the explicit typing.
1.5 KiB
1.5 KiB
Mutex
Mutex<T>
ensures mutual exclusion and allows mutable access to T
behind a read-only interface:
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());
}
Notice how we have a impl<T: Send> Sync for Mutex<T>
blanket
implementation.
Mutex
in Rust looks like a collection with just one element - the protected data.- It is not possible to forget to acquire the mutex before accessing the protected data.
- You can get an
&mut T
from an&Mutex<T>
by taking the lock. TheMutexGuard
ensures that the&mut T
doesn't outlive the lock being held. Mutex<T>
implements bothSend
andSync
iffT
implementsSend
.- A read-write lock counterpart -
RwLock
. - Why does
lock()
return aResult
?- If the thread that held the
Mutex
panicked, theMutex
becomes "poisoned" to signal that the data it protected might be in an inconsistent state. Callinglock()
on a poisoned mutex fails with aPoisonError
. You can callinto_inner()
on the error to recover the data regardless.
- If the thread that held the