Reader-Writer Problem

Reader-Writer Problem using Semaphore

Reader() { // multiple readers can read the data at the same time when there is no writer

P(rmutex); // lock for nreaders
nreaders++; // # of reader count increase
if (nreaders == 1) P(rwmutex); // if there is the first reader, lock writer mutex (reader들이 읽는 동안 writer는 접근 못하도록)
V(rmutex); // unlock for nreaders

<<< critical section: Read data  >>> reader들은 writer가 사용하지 않을시 동시에 여러 개가 접근 가능

P(rmutex); // lock for nreaders
nreaders–; // # of reader count decrease
if (nreaders == 0) P(rwmutex); // if there is no reader, unlock writer mutex (reader가 더이상 없으면 writer가 접근 가능하도록)

V(rmutex); // unlock for nreaders

}

Writer() { // only one writer can write data at a time when there is no reader

P(rwmutex); // lock writer mutex

<<< critical section: Writer data >>>writer는 reader가 사용하지 않을시 한번에 하나씩 접근 가능

V(rwmutex); // unlock for writer mutex
}