Readers and Writers
Andrews Chapter 4
Problem Definition
Two kinds of threads (processes) wish to
access a common data item or items. Readers only need to read the data and
writers can read and write the data. Multiple readers can access the data
simultaneously but writers must have exclusive access to the data to write it.
Reader/Writer Solutions
int nr
=0; # number of active readers
sem rw =1
# lock for readers and writer exclusion
process Reader [i = 1 to M] {
while (true) {
...
<nr =nr + 1;
if (nr == 1) P(rw);
# if first reader you get the lock
>
read the database;
< nr = nr-1;
if (nr == 0) V(rw);
# if last reader, release the lock
>
}
}
process Writer [ j = 1 to N] {
while (true) {
...
P(rw);
write the database;
V(rw);
}
}
int nr =
0; # number of active readers
sem rw =1; #lock for
access to the data
sem mutexR =
1; #lock for readers access to
"nr"
process Reader [i =
1 to m] {
while (true) {
...
P(mutexR);
nr = nr = nr + 1;
if (nr == 1 ) P(rw);
# if first reader, you get the lock
V(mutexR);
read the database;
P(mutexR);
nr = nr - 1;
if (nr == 0) V(rw);
# if last reader, give up the lock
V(mutexR);
}
}
process Writer [j = 1 to n] {
while (true) {
...
P(rw);
# only one writer gets access to database
write the database;
V(rw);
}
}