Monitor
Monitor
상호 배제(mutual exclusion)가 필요한 블록을 위한 잠금(lock) 객체가 필요할 때 Monitor 클래스를 사용해요.
출처: Ruby 3.3 API
본문
require 'monitor'
lock = Monitor.new
lock.synchronize do
# exclusive access
end
Monitor 객체는 synchronize 블록 안에서만 한 번에 하나의 스레드가 코드를 실행하도록 보장해 줘요.
Public Instance Methods
enter()
잠금을 획득해요. (mon_enter로도 별칭돼 있어요.)
exit()
잠금을 해제해요. (mon_exit로도 별칭돼 있어요.)
mon_check_owner()
현재 스레드가 잠금의 소유자인지 검사해요.
mon_enter()
enter의 별칭이에요.
mon_exit()
exit의 별칭이에요.
mon_locked?()
잠금이 걸려 있으면 true를 돌려줘요.
mon_owned?()
현재 스레드가 잠금을 소유하고 있으면 true를 돌려줘요.
mon_synchronize()
synchronize의 별칭이에요.
mon_try_enter()
try_enter의 별칭이에요.
new_cond()
이 모니터에 연결된 조건 변수(ConditionVariable)를 새로 만들어요.
synchronize()
블록을 실행하는 동안 잠금을 보유해요. (mon_synchronize로도 별칭돼 있어요.)
require 'monitor'
lock = Monitor.new
lock.synchronize do
# 배타적으로 실행되는 영역
end
try_enter()
잠금 획득을 시도하고, 실패하면 false를 돌려줘요. (try_mon_enter, mon_try_enter로도 별칭돼 있어요.)
try_mon_enter()
호환성을 위해 있는 메서드예요. try_enter의 별칭이에요.
wait_for_cond(p1, p2)
조건 변수를 기다리는 내부 메서드예요.
더 알아보기
- 모니터를 믹스인으로 제공하는
MonitorMixin문서도 함께 보세요.