I know may be i bored you with basic semaphores and semaphore problems;but I hope it will be useful for the people who are just introducing with them.
Reader Writer Problem with Semaphores:
If one process is reading an object , other processes can read it too ;but they can not write or modify this object .
Generally the case is like that:
While Writing -> Can't write or read the object
While Reading->Can read ;but can not modify the object.
Shared Data:
semaphore mutex , wrt;
int readcount;
//Initially
mutex=1 , wrt =1, readcount=0;
Writer:
wait(wrt);//wrt-- , wrt=0;
writeToFile();//...Writing is performed
signal(wrt);//wrt++ , wrt=1;
While wrt=1 the writing process can be done by other processes.
While wrt=0 the other processes can not write to the object.
The reader process is a bit more complex.
Reader:
wait(mutex);//mutex--, mutex=0
readcount++;// readcount=1
if(readcount==1)
{wait(wrt);}
signal(mutex);
readTheObject();//...Reading is performed
wait(mutex);
readcount--; // readcount=0;
if(readcount==0) //Check if the reading is performed
signal(wrt);
signal(mutex);
The codes between wait(mutex) and signal(mutex) are the places where we don't want other processes access to avoid ambiguousness.
An Example about how this code works:
1 2 3
Reader1:readcount=1,wrt=0,readcount=1 .
Reader2:readcount=2,wrt=0, readcount=0,wrt=1.
Writer: writing, writing is finished.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment