class ReadWriter{
int Rcount=0;
Semaphore writeSem = new Semaphore(1);
Semaphore mutex= new Semaphore(1);
Data data;//数据
public void writerMethod(data){
writeSem.acquire();
//todo write the data;
writeSem.release();
}
public void readMethod(data)
//凡是涉及Rcount 都要用互斥保证安全
mutex.acuire();
if(Rcount==0){
writeSem.acquire();
}
Rcount++;
mutex.release();
// todo read the data
mutex.acquire();
Rcount--;
// 只有最后的一个离开读,才有资格释放读写互斥锁
if(Rcount==0){
writeSem.release();
}
mutex.release();
}
随笔---信号量实现,读共享,读写互斥,写写互斥,读优先,锁模型
最新推荐文章于 2021-07-27 17:44:58 发布