RwLock — 읽기-쓰기 잠금
RwLock — 읽기-쓰기 잠금
RwLock<T>는 읽기-쓰기 잠금(reader-writer lock) 동기화 프리미티브예요. 여러 읽기와 하나의 쓰기를 허용해요.
출처: Rust 공식 문서
본문
pub struct RwLock<T: ?Sized> { /* private fields */ }
주요 메서드
pub const fn new(t: T) -> RwLock<T>
pub fn read(&self) -> LockResult<RwLockReadGuard<'_, T>>
pub fn try_read(&self) -> TryLockResult<RwLockReadGuard<'_, T>>
pub fn write(&self) -> LockResult<RwLockWriteGuard<'_, T>>
pub fn try_write(&self) -> TryLockResult<RwLockWriteGuard<'_, T>>
pub fn get_mut(&mut self) -> LockResult<&mut T>
예시
use std::sync::RwLock;
let lock = RwLock::new(5);
{
let r1 = lock.read().unwrap();
let r2 = lock.read().unwrap(); // 읽기 여러 개 허용
}
{
let mut w = lock.write().unwrap();
*w += 1;
}
read는 여러 스레드가 동시에 읽을 수 있게 하고, write는 한 스레드만 배타적으로 쓸 수 있게 해요. 쓰는 동안 다른 읽기/쓰기는 블록돼요. 스레드가 잠금을 보유한 채 패닉하면 독(poison)돼요.