Reader Writer Problem

Problem Statement

The reader-writer problem is a classic synchronization problem in concurrent programming that involves two types of processes: readers and writers. These processes access a shared resource, such as a database or a file, under certain constraints. The problem can be summarized as follows:

  1. Readers: Multiple readers can access the shared resource simultaneously without any issues. They only read the resource and do not modify it. Readers can access the resource concurrently as long as no writer is currently writing to it.

  2. Writers: Writers are exclusive; only one writer can access the resource at a time. Writers have the authority to modify the shared resource. While a writer is writing to the resource, no other readers or writers are allowed access.

The primary goals of the reader-writer problem are:

  • Allow multiple readers to access the resource concurrently for reading (readers-writers concurrency).

  • Ensure exclusive access for writers to prevent multiple writers from modifying the resource simultaneously (writers-writers mutual exclusion).

  • Avoid the possibility of writers starving, meaning that if a writer is waiting to access the resource, it should eventually get a chance, even if new readers keep arriving (fairness).

Solution :

  1. Mutex : Binary semaphore to ensure mutual exclusion , when read count ( rc ) is updated

  2. wrt : Binary Semaphore common for both reader and writer , to maintain mutual exclusion between reader & writer.

  3. read count ( rc ) : interger , to keep record of how many readers are there

Writer :

do {
    
    wait( wrt ); // wait till no reader is reading the item
    
    // start critical section
    write();
    // end critical section
    
    signal( wrt ); // notify the rest 
    
}while( True );

Reader :

do{
    
    wait( mutex ); // wait till no reader is updating rc
    
    rc++; // update rc
    
    if(rc == 1 ) // if rc is incremented from 0 , lock wrt
    {
        
        wait( wrt ); // lock wrt , no writer can now write the data
    }
    
    signal( mutex ); // signal the reader 
    
    // Critical Section: Reader is reading
    read();
    
    wait( mutex ); // wait till no reader is updating rc
    
    rc--; // update rc
    
    if( rc == 0 ) // if rc == 0 , release wrt
    {
        
        signal( wrt ); // release wrt lock
    }
    
    signal( mutex ); // signal the reader 

    
} while( True );

Last updated