Mutex
Mutex<T>๋ฅผ ์ด์ฉํ๋ฉด ๋ถ๋ณ ์ฐธ์กฐ๋ฅผ ํตํด์๋ T์ ๊ฐ์ ์์ ํ ์๊ฐ ์์ผ๋ฉฐ, ์ด์ ๋ํด์ ํ ๋ฒ์ ํ ์ค๋ ๋๋ง T์ ๊ฐ์ ์ ๊ทผ(์ฝ๊ฑฐ๋ ์ฐ๊ฑฐ๋)ํจ์ ๋ณด์ฅํด ์ค๋๋ค:
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()); }
๋ชจ๋ Mutex<T>๋ impl<T: Send> Sync for Mutex<T>๋ฅผ ์๋์ผ๋ก ๊ตฌํํจ์ ์ฐธ์กฐํ์ธ์.
Mutexin 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 Tfrom an&Mutex<T>by taking the lock. TheMutexGuardensures that the&mut Tdoesnโt outlive the lock being held. Mutex<T>implements bothSendandSynciff (if and only if)TimplementsSend.- A read-write lock counterpart -
RwLock. - Why does
lock()return aResult?- If the thread that held the
Mutexpanicked, theMutexbecomes โ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