There are four conditions that must be satisfied by any reader-writer problem solution
- When a reader is reading, no writer must be allowed.
- Multiple readers should be allowed.
- When a writer is writing, no reader must be allowed.
- Multiple writers$($more than $1)$ should not be allowed.
Now, here mutex is a semaphore variable that will be used to modify the variables $R$ and $W$ in a mutually exclusive way.
The reader code should be like below
Reader()
L1: wait(mutex);
if(w==0){ //no Writer present, so allow Readers to come.
R=R+1; //increment the number of readers presently reading by 1.
signal(mutex);//Reader is allowed to enter,
//number of readers present "R"
//is incremented and now make mutex available so that other readers
//can come.
}
else{ //means some writer is writing,so release mutex, and try to
//gain access to mutex again by looping back to L1.
signal(mutex);
goto L1;
}
/*reading performed*/
wait(mutex);
R=R-1;
signal(mutex);
Value of variable $R$ indicates the number of readers presently reading and the value of $W$ indicates if $1,$ that some writer is present.
Writer code should be like below
Writer()
L2: wait(mutex);
if(R>0 || W!=0) //means if even one reader is present or one writer is writing
//deny access to this writer process and ask this to release
//mutex and loop back to L2.
{
signal(mutex);
goto L2;
}
//code will come here only if no writer or no reader was present.
W=1; //indicate that a writer has come.
signal(mutex); //now after updating W safely, release mutex, for other writers and
//readers to place their request.
/*Write performed*/
//writer will leave so change Value of W in a mutual exclusive manner.
wait(mutex);
W=0;
signal(mutex);
This will satisfy all requirements of the solution to the reader-writer problem.
(B) Yes, writers can starve. There can be the scenario that whenever a writer tries to enter, it finds some reader $(R!=0),$ or another writer process $(W!=0)$ and it can keep waiting forever. Bounded Waiting for the writer's processes is not ensured.