모니터(Monitor)는 공유 자원과 그 자원에 접근하는 프로시저를 하나의 모듈로 묶어, 상호 배제와 조건 동기화를 자동으로 제공하는 고수준 동기화 구조다. Java의 synchronized 키워드가 모니터를 구현한 대표적 예다.
구성 요소
모니터 = 공유 데이터
+ 진입 잠금 (Mutex)
+ 조건 변수 (Condition Variable) 집합
+ 내부 프로시저들
Java 모니터 (synchronized)
java
class BoundedBuffer {
private int[] buf = new int[10];
private int count = 0, in = 0, out = 0;
public synchronized void put(int val) throws InterruptedException {
while (count == buf.length)
wait(); // 잠금 해제 + 대기
buf[in] = val;
in = (in + 1) % buf.length;
count++;
notifyAll(); // 대기 중인 스레드 깨우기
}
public synchronized int get() throws InterruptedException {
while (count == 0)
wait();
int val = buf[out];
out = (out + 1) % buf.length;
count--;
notifyAll();
return val;
}
}
조건 변수 (Condition Variable)
모니터 내에서 특정 조건이 만족될 때까지 스레드를 대기시키는 메커니즘.
python
import threading
lock = threading.Lock()
not_empty = threading.Condition(lock)
buffer = []
def producer():
with not_empty:
buffer.append(1)
not_empty.notify() # 대기 중인 소비자 깨움
def consumer():
with not_empty:
while not buffer:
not_empty.wait() # 빈 경우 대기 (잠금 임시 해제)
return buffer.pop()
wait/notify 시멘틱스
| 연산 | 설명 |
|---|
| wait() | 잠금 해제 + 조건 큐에 대기 |
| notify() | 조건 큐에서 스레드 1개 깨움 |
| notifyAll() | 모든 대기 스레드 깨움 |
관련 개념
- •뮤텍스 — 모니터의 내부 잠금
- •세마포어 — 저수준 동기화 원시 연산
- •데드락 — wait/notify 오용 시 발생
- •동시성 — 모니터가 해결하는 문제