读写者

首先是读写者问题,这个允许多个读者同时读,然而当读者读的时候,写着不允许写;但多个读者可以同时doReading();而当写者写的时候,读者不允许读;

int readCount = 0 , writeCount = 0 ; 
Semaphore wsem = 1 ;
Semaphore mutex = 1 ;

void Reader() {
while(true) {
  // lock the mutex to avoid the consurrent modification of readCount ;
wait(mutex) ;
readCount ++ ;
if (readCount == 1) {
wait(wsem) ;
}

// then other readers can come in , however , writer can't come in , for some readers is still reading .
signal(mutex) ;

doReading() ;

// lock the mutex to avoid the consurrent modification of readCount ;
wait(mutex) ;

readCount -- ;
if (readCount == 0) {
signal(wsem) ;
}

signal(mutex) ;
}
}

void Writer() {
while (true) {
wait(wsem) ;
doWriting() ;
signal(wsem) ;
}
}

但是,在上述中,如果读者源源不断的来的话,就会造成读者会一直读下去,导致没法写数据;

此时需要写优先的算法:

int readCount = 0 , writeCount = 0 ; 
Semaphore rsem , wsem ;

void Reader() {
Semaphore mutex , pre_mutex ;
while (true) {
// guarantee the precedence of the writer ;
wait(pre_mutex) ;
//judge if a writer process in the critical region , if so , just wait ; otherwise no new writer process will be in ;
wait(rsem) ;
// lock the mutex to avoid the consurrent modification of readCount ;
wait(mutex) ;
readCount ++ ;
if (readCount == 1) {
// 第一个读进程需要判断是否有写进程在进行写操作,有的话需要等待,没有的话不让写进程进行新写操作;

wait(wsem) ;
}
// end the mutex visit of readCount ;
signal(mutex) ;
// the return the read lock , so the writer can come in the critical region if there existed ;
signal(rsem) ;
signal(pre_mutex) ;

doReading() ;

wait(mutex) ;
readCount -- ;
if (readCount == 0) {
signal(wsem) ; //最后一个离开临界区的读进程需要归还锁,让写进程可以进行写操作;
}
signal(mutex) ; //结束对readcount的互斥访问 ;
}
}

void Writer() {
Semaphore mutex , pre_mutex ;
while (true) {
wait(mutex) ; //开始对writecount的互斥访问;
writeCount ++ ; // 更新写进程的数量;
if (writeCount == 1) {
/*
第一个写进程需要判断是不是有读进程在临界区,有的话需要等待 ;
没有的话不让新的读进程进来;
*/
wait(rsem) ;
}
signal(mutex) ; // 结束对writeCount的互斥访问

wait(wsem) ; // 限制同一时刻对写进程的访问(写者互斥),以及此时如有读进程读的话,则同样不能写 ;
doWriting() ;
signal(wsem) ; // 结束对写进程的限制 ;

wait(mutex) ;
writeCount -- ;
if (writeCount == 0) {
//最后一个离开临界区的写进程需要归还锁,让读进程可以进临界区
signal(rsem) ;
}
signal(mutex) ;
}
}
原文地址:https://www.cnblogs.com/diyingyun/p/2274965.html