## main mega menu

##### Reader writer problem

Readers Writer Problem

Readers writer problem is another example of a classic synchronization problem. There are many variants of this problem, one of which is examined below.

Problem Statement:

There is a shared resource which should be accessed by multiple processes. There are two types of processes in this context. They are reader and writer. Any number of readers can read from the shared resource simultaneously, but only one writer can write to the shared resource. When a writer is writing data to the resource, no other process can access the resource. A writer cannot write to the resource if there are non zero number of readers accessing the resource.

Solution:

From the above problem statement, it is evident that readers have higher priority than writer. If a writer wants to write to the resource, it must wait until there are no readers currently accessing that resource.

Here, we use one mutex m and a semaphore w. An integer variable read_count is used to maintain the number of readers currently accessing the resource. The variable read_count is initialized to 0. A value of 1 is given initially to m and w.

Instead of having the process to acquire lock on the shared resource, we use the mutex m to make the process to acquire and release lock whenever it is updating the read_count variable.

code:-

The code for the writer process:

while(TRUE) {
wait(w);
/*perform the
write operation */
signal(w);
}


The code for the reader process:

while(TRUE) {
wait(m);   //acquire lock
read_count++;
if(read_count == 1)
wait(w);
signal(m);  //release lock
/* perform the
reading operation */
wait(m);   // acquire lock
read_count--;
if(read_count == 0)
signal(w);
signal(m);  // release lock
} 
##### Readers Writers Problem

Readers Writers Problem

If we have shared memory or resources, then readers - writers can create conflict due to these combinations: writer - writer and writer- reader access critical section simultaneously that create synchronization problem, loss of data etc. We use semaphores to avoids these problems in reader writer problem.

We follow some concepts using semaphore to solve readers - writers problem: reader and writer can not enter into critical section at same time. Multiple reader can access critical section simultaneously but multiple writer can not access.

 Shared Data: Semaphore mutex = 1 ; Semaphore wsem = 1 ; int readcount = 0 ; Reader Process: Reader () { While (true) { Wait (mutex) ; Readcount ++ ; If (readcount = = 1) Wait (wsem) ; Signal (mutex) ; // Critical Section () ; Wait (mutex) ; Readcount - - ; If (readcount = = 0) Signal (wsem) ; Signal (mutex) ; } } Writer Process: Writer () { While (true) { Wait (wsem) ; // Critical Section () ; Signal (wsem) ; } }

Semaphore ‘mutex’ ensures mutual exclusion property. Readcount and wsem ensures that there is no conflict in the critical section problem. These avoids race around, loss of data, and synchronization problem.