tags:

views:

71

answers:

3

Hi,

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 is my Question : 1. What is the purpose of line A in the leader code? 2. Can we eliminate that line and the code work correctly?

A: 

First of all, the code is wrong: you need to execute if (rc ==0) V(db) under locked mutex.

The line A is needed in order to lock the database for reading. Lock is set at the first reading operation, and released after the last one; as well it's set during each of the possible writing operations. If the lock won't be set, the read and write operation could be executed simultaneously, which results in corrupt data.

Vlad
Are you sure that the code is wrong? Can you tell an example, where an error would occur?
3lectrologos
i also think it's wrong..thread 1:// assume rc == 0V(mutex);switch to thread 2:P(mutex); rc++; // now rc == 1switch to thread 1:if (rc ==0) V(db); // rc is already 1 so it forgets to V(db).
stmax
Of course. Imagine that a reader #1 comes in thread #1, and executes till the line `if (rc ==0) V(db);` (but not including it). Now context switches to thread #2. In the thread #2 comes another reader, locks the mutex, increments `rc`, now the value of `rc` is 2. Therefore the second reader doesn't lock `db`. Now context switches to thread #3, in this thread a writer tries to lock the db, obtains the lock, and modifies the data which are currently being read by the thread #2. So the data will be corrupted.
Vlad
+1  A: 
  • 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.
3lectrologos
A: 

The writer should not write while anybody is reading. Therefore any reader blocks db while he reads, if he is the early bird (#1). And he has to clean up the blockade if he is the last guy in the room (rc == 0) as well.

ypnos