Reader-Writer Problem in Operating System with Code

The readers and writers problem based on an object like a file which is shared in different processes. Some processes are readers so that they can only read the data and some processes are writers so that they can only write the data. This problem is generally used to manage synchronization. 

A writer should achieve exclusive access to the object for solving the readers-writers problem. When one writer is accessing the object or file, no other readers or writers should access that object or file. Many readers can access the object or file to read at a single time. But the problem is when two or more writers and a reader are trying the access same file or object.

This is where the initial reader blocks when there is a writer; other readers who want to come in will be blocked on the mutex. When there is reader and writer both exits then which goes to work next depends on the scheduler. All readers who are waiting will break down when a writer occurs, and the reader goes next. 

We used two variables of the semaphore to solve Readers and Writers problems

  • Semaphore “writer”: To achieve the mutual exclusion property, we used semaphore “writer”. This semaphore is used by the process, which is writing in the file. It assures that no any other process should come in the critical section at that instant of time. 
  • Semaphore “Reader”: During altering the variable which is containing the count of the process, which are reading a separate file, we used this semaphore to achieve mutual exclusion. 

Code For the Reader & Writers

The code for Reader Process

if (rc == 0);
signal (wrt);
signal (mutex);

Here, mutex and wrt are semaphores.

The code for the writer process

wait (mutex);
signal (wrt);

When a writer needs to access the object, wait for operation functions on wrt. If the writer is completed writing then the signal operation functions on wrt.