while(true){
/* produce an item in next_poduced */
wait(empty); //비어있는 지 검사
wait(mutex); //임계 구역에 대한 락 확보
/* add next_produced to the buffer */
signal(mutex); // 임계 구역에 대한 락 반남
signal(full); // 채워진 버퍼 표기
while(true){
wait(full); //사용가능한 버퍼가 있는지 확인
wait(mutex); // 임계구역에 대한 락 확보
/* remove an item from buffer to next_consumed */
signal(mutex); //임계구역에 대한 락 반남
signal(empty); //자원을 사용하여 empty 구역이 생겼음을 알림
/* consumed the item in next_consumed */
⇒ 소비자와 생산자가 대칭구조임을 알 수 있다.
몇 명이 읽든 상관이 없지만 Writer가 쓰고 있는데 Reader들이 읽으면 동시성이 깨질 수 있다 두 가지의 경우를 골라 우선순위에 맞춰서 해당 문제를 해결하기 위한 구현마다 다를 수 있다.
writer가 기다리고 있을 때 reader들은 마냥 기다리기만 해서는 안 된다.
→ writer가 기아 상태에 빠질 수 있다.
writer가 객체에 접근하려 할 때 새로운 reader들은 읽기 시작하지 못한다.
→ reader가 기아 상태에 빠질 수 있다.
이를 해결하기 위해 세 개의 제어변수로 위 문제들을 해결한다.
writer code
while (true) {
wait(rw_mutex)
....
/* writing is performed*/
signal(rw_mutex)
}
while (true) {
wait(mutex);
read_count++;
if (read_count == 1)
wait(rw_mutex);
signal(mutex);
/* reading is performed */
wait(mutex);
read_count--;
if(read_count == 0)
signal(rw_mutex);
signal(mutex);
}