Readers Precedence
when both readers and writers wait,favor readers and writers can write only after all readers read.Using semaphore me1 to let writer need to wait one more signal.e.g.when
writer w1 enters and no readers,w1 can write,then have both writers and readers are waiting. Reader r1 can continue till wait(w),but writer w2 can‘t enter because it needs w1
completes to release semaphore(me1).After w1 finishes writing,it releases semaphore w first,then reader r1 gets immediately. Then reader r1 increases counter,and release semaphore me later which can let next reader increases counter,in this way till last reader
finishes reading and decreases(nr==0) counter,semaphore w can only be released.Only after this,can writer gets semaphore w and writes.
nr=0(number of readers currently reading)
int(w)=int(me)=int(me1)=1
Reader Writer
wait(me); wait(me1)
nr++; wait(w)
if(nr==1) wait(w) ...
signal(me) //writing
... ...
//reading signal(w)
... signal(me1)
wait(me)
nr--;
if(nr==0) signal(w)
signal(me)
Writers Precedence
The use of me2 is same with previous case
nr=nw=0;init(r)=init(w)=init(me)=init(me1)=init(me2)=1
Reader Writer
wait(me2) wait(me1)
wait(r) nw++
//needs to see whether there‘s writer if(nw==1) wait(r)
//waiting,previous only first reader needs to check signal(me1)
//and checks only writing wait(w)
wait(me) .
nr++ .
if(nr==1) wait(w) //Writing
signal(me) .
signal(r) .
signal(me2) signal(w)
//Reading wait(me1)
wait(me) nw--
nr-- if(nw==0)signal(r)
if(nr==0) signal(w) signal(me1)
signal(me2)
when no precedence for both readers and writers,but first in,first served,what to do?
maybe list
System and device programming——R&W with semaphore