Operating System: Readers write the problem

Operating system: read write the problem

A data file or records can be shared by multiple processes.

Read-only process for the "reader process," other processes "writer process."

It allows multiple objects simultaneously reading a shared object, but does not allow a reader writer process and other processes at the same shared object.

Use record of semaphores solve the problem readers and writers

Mutex wmutex: realize mutual exclusion between reader and writer processes read or write,

Integer variable readcount: represents the number of processes being read.

Because as long as there is a reader in the reading process, you can neither writer writing process.

Therefore, only when readcount = 0, ie no reader in the process of reading, reader only needs to be performed wait (wmutex) operation,

If the wait (wmutex) operation is successful, reader process will be able to read, accordingly, do readercount + 1 operation.

Similarly, only when the reader process after performing a readcount-1 operating its value is 0, only need to perform signal (wmutex) operation, so that the process of writing writer

Mutex rmutex: mutual exclusion between reader access readcount

to sum up:

wmutex: mutex semaphore when reading and writing.

The amount of signal is read mutual exclusion of access readcount: rmutex
 

Readers priority, will cause hunger writer. (Readers priority means that unless there is a writer to write files, or readers need not wait)

 

semaphore wmutex=1;//读写互斥,写写互斥
semaphore rmutex=1;读间访问readcount互斥
int readcount=0;读者进程数
 
reader{
   while(true){
 
     wait(rmutex);获取读间访问readcount互斥信号量
     if(readcount==0)如果之前没有读进程,则先获取读写互斥信号量,对readcount加1,
     wait(wmutex);
     ++readcount;
     signal(rmutex);readcount加1操作完后释放读间访问readcount互斥信号量,开始读
     read;
     wait(rmutex);读完后,对readcount操作加锁,执行readcount减1操作
     --readcount;
     if(readcount==0)没有读进程后,就释放读写互斥锁
     signal(wmutex);
     signal(rmutex);
   }

}
 
writer{
    while(true){
       wait(wmutex);
       write;
       ignal(wmutex);
    }

}

 

Published 736 original articles · won praise 123 · views 80000 +

Guess you like

Origin blog.csdn.net/S_999999/article/details/103647722