This is the reader-writer problem for just read consistency.
Here is the algorithm:
void reader() {
while (1) {
P(mutex);
rc++;
if (rc == 1) P(db); /* <---- A */
V(mutex); /* <---- B */
read_data_base();
P(mutex);
rc--;
V(mutex);
if (rc == 0) V(db);
}
}
void writer() {
while (1) {
P(db);
write_data_base();
V(db);
}
}
Here are my questions:
1. What is the purpose of line A in the reader code?
2. If we eliminate that line will the code still work correctly?
The purpose of line A, is to check if the current reader is the first one after a write (or the first one overall). If this is the case, then he has to obtain the database mutex (db), so that no writer can write to the database, while there is at least one reader reading it.
The corresponding line for the last reader is:
if (rc == 0) V(db);The purpose of this line, is to check if the current reader is the last reader, so that a writer can enter next (if there isn’t another reader that enters before the writer).
Based on the above description, if you eliminate line A, your code won’t work correctly.
Note: As seen in Vlad’s answer below (and the discussion in the comments thereof),
V(mutex)should be afterif (rc == 0) V(db).