I am trying to implement a solution for reader-writers problem with readers preference. Following is the problem statement:
- Data is shared between one writer thread and multiple reader threads
- Reader thread should wait if writer thread is accessing the shared data.
- Reader thread should not wait if another reader thread is is accessing the shared data
I have come up with the following pseudo-code.
Can somebody tell me if the following solution is adequate and what are the issues with it ?
initialize()
{
initialize semaphore with value 0
initialize reader_active_count with value 1
}
writer()
{
// Wait until reader thread makes the semaphore non-zero
sem_wait(s)
write data;
sem_post(s)
}
reader()
{
lock(r1)
reader_active_count ++;
// Am I the first reader thread
if (reader_active_count == 1)
{
// Wait until writer thread makes the semaphore non-zero
sem_wait(s);
}
unlock(r1)
read data
lock(r1)
reader_active_count--;
// Am I the last reader thread
if(reader_active_count == 0)
{
// Increment the sempahore to a non-zero value
sem_post(s);
}
unlock(r1)
}