Monitor

개발새발log·2023년 5월 9일
0

쉬운 코드 님의 영상을 보고 정리한 글 입니다

Monitor란?

In concurrent programming, a monitor is a synchronization construct that allows threads to have both mutual exclusion and the ability to wait (block) for a certain condition to become false

출처: 위키백과 Monitor

  1. mutual exclusion 보장
  2. 조건에 따라 스레드를 waiting 상태로 전환

하는 책임을 가진 스레드 간 동기화 보장 방식이다.

구성 요소

✔️ Mutex (Lock) : Critical Section에 하나의 스레드만 들어가도록

✔️ Condition variables : 대기 상태의 스레드들을 담은 waiting queue를 가진다

동작 방식

	mutex lock 획득 (다른 스레드들은 entry queue에서 대기)

	(조건을 만족하지 못하는 동안) wait (= waiting queue에서 대기)
	(조건 만족 시) signal/broadcast (=다른 스레드(들) 깨움)

	mutex lock 반환

👉 2개의 큐

  • entry queue : critical section의 진입을 기다리는 큐
  • waiting queue : 조건이 충족되길 기다리는 큐

Producer-Consumer Problem

Producer 스레드들은 버퍼에 스레드를 enqueue 한다. 다만, 큐가 꽉 찼을 때 더 이상 enqueue 하지 못한다.

Consumer 스레드들은 버퍼에서 스레드를 dequeue 한다. 다만, 큐가 비었을 때 dequeue 하지 못한다.

여기서 Producer와 Consumer가 가진 딜레마는 ?

✔️ Producer: 큐가 꽉 찼을 때, 계속 돌면서 확인해야 할까 ?
✔️ Consumer: 큐가 비어있을 때, 계속 돌면서 확인해야 할까 ?

Monitor를 활용한 문제 해결

Producer

while (q.isFull()) wait(lock, fullCV);

q.enqueue(t1);

signal(emptyCV);

Consumer

while (q.isEmpty()) wait(lock, emptyCV);

t1 = q.dequeue();

signal(fullCV);
profile
⚠️ 주인장의 머릿속을 닮아 두서 없음 주의 ⚠️

0개의 댓글