Operating system reader writer synchronization problem

There are two groups of concurrent processes between readers and writers, sharing a file. When two or more readers access shared data at the same time, there will be no side effects, but if a writer process and other processes access shared data at the same time, it may cause data inconsistency. The error, therefore, requires:

  1. Allow multiple readers to perform read operations on files at the same time
  2. Only one writer is allowed to write information to the file
  3. No other readers or writers are allowed to work before any writer completes the writing operation
  4. Before the writer performs the write operation, all existing readers and writers should be allowed to exit

The following algorithm is the priority of the reading process, because it may cause starvation of the writing process

//用于实现对共享文件的互斥访问
seamaphore rw =1;
//记录当前有几个读进程在访问文件
int count = 0;
//由于对count的访问也是不确定的,所以也要设置信号量来对count进行互斥访问
seamaphore mutex =1;
//为了解决写进程可能会饿死的问题,新设置一个信号量,用于实现写优先
seamphore w = 1;
write(){
    while(1){
        P(w);
        P(rw);//写操作之前先上锁
        写文件操作
        V(rw);//写完之后解锁
        V(w);
    }
}
reader(){
    while(1){
        P(w);
        P(mutex);
        if(count==0)//由第一个读进程来进行上锁操作
            P(rw);
        count++;//统计读进程数量
        V(mutex);
        V(w);
        读文件
        P(mutex);
        count--;
        if(count==0)//由最后一个读进程来进行解锁
            V(rw);
        V(mutex);
    }
}

 

Guess you like

Origin blog.csdn.net/qq_20176001/article/details/100105066