======================================================================
readers are prior
[analyse:]
writer:
can't write when anyone is reading. exclusive
readers:
when one of the readers are reading, the readers who want to read can
read.
but them can't read when the writer is writing. exclusive
the action to change the readcount and the lock made the reader and
writer exclusive are exclusive.
======================================================================
//the reason why the readcount is not a semaphore is that it was
// a condition ,and not a semaphore make the process exclusive
int readcount = 0;
semaphore mutex = 1, w = 1;
reader(){
while(1){
wait(mutex);
if(readcount == 0)
wait(w); \\读者读的时候互斥
readcount++;
signal(mutex);
读;
wait(mutex);
readcount--;
if(readcount == 0)
signal(w);
signal(mutex);
}
}
writer(){
while(1){
wait(w);
写;
siganl(w);
}
}
======================================================================
the writer is prior
[analyse:]
writer:
writer is one can write, but them have a list to block.
if there is a writer who is writing, others can push into the list
and wait for invoke.
else
they should be blocked by the lock
reader:
many and need read at seem time
but them can't read when the writer is writing. exclusive
======================================================================
siganl 和 wait() 本身就是原子性的。
int readcount = 0;
int writecount = 0;
semaphore w = 1, r = 1, mutex1 = 1, mutex2 = 1, mutex3 =1;
reader(){
while(1){
wait(metux3);
wait(r); //互斥r的
wait(metux1);
if(readcount == 0)
wait(w); //我们还没读完,你们可以进来但是你别写啊!
readcount++;
signal(mutex1);
signal(r);
读;
wait(mutex1);
readcount--;
if(readcount == 0)
signal(w);
signal(mutex1);
signal(metux3);
}
}
writer(){
while(1){
wait(mutex2);
if(writecount == 0)
wait(r);
writecount ++;
signal(mutex2);
wait(w); //我们还没读完,你们可以进来但是你别写啊!
写;
signal(w);
wait(mutex2);
writecount--;
if(writecount == 0)
signal(r);
signal(mutex2);
}
}