Many times, we see that there are multiple readers wanting to get the values and few writers who changes the value. For example, in a firewall policy, there will be occasional change of policy. However, policy will be evaluated whenever a data packet arrives.
Similarly for a website showing news, reading will happen more often than writing news. In such cases, it is more important to give some advantage to read operation over write.
Shared variables: Semaphore mutex, wrl;
integer rcount;
Init: mutex = 1, wrl = 1, rcount = 0;
Writer
do {
P(wrl);
. . .
/*writing is performed*/
. . .
V(wrl);
}while(TRUE);
Reader
do {
P(mutex);
rcount++;
if (rcount == 1)
P(wrl);
V(mutex);
. . .
/*reading is performed*/
. . .
P(mutex);
rcount--;
if (rcount == 0)
V(wrl);
V(mutex);
}while(TRUE);
Input: mutex m, condition variable c, integer r (number of readers waiting), flag w (writer waiting).
Lock m (blocking).
While w:
Increment r.
Unlock m.
wait c, m[a]
Lock m (blocking).
While (w or r > 0):
Set w to true.
Unlock m.
wait c, m
https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock
http://heather.cs.ucdavis.edu/~matloff/158/PLN/RWLock.c
www.cs.cornell.edu/courses/cs414/2007sp/lectures/09-syncproblems.ppt
http://heather.cs.ucdavis.edu/~matloff/158/PLN/RWLock.c
https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock