讀者—寫者問題是操作系統併發同步的經典模型,第二類(也稱「寫者优先」)要求:一旦有寫者等待,後續的讀者必須排隊,不許插隊。下面用 Java 結合信號量(Semaphore)給出一份可運行的實現。
先自己實現一個簡單信號量,用計數器記錄可用資源數,P 操作申請(減一,不足則等待),V 操作釋放(加一,喚醒等待者):
package rw;
public class Semaphore {
private int value;// 記錄希望訪問臨界資源的線程計數器個數
public Semaphore(int i) {
this.value = i;
}
public synchronized void P() {
value--;
if (value < 0)
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
public synchronized void V() {
value++;
if (value <= 0) {
notifyAll();
}
}
}
主類通過幾個信號量協調讀寫:mutex 保護寫者計數、mutexr 保護讀者計數、mutexWrite 保證讀寫互斥、mutexw 保護寫者計數的更新。核心在於:第一個進來的讀者要申請 mutexWrite 以排斥寫者,最後離開的讀者釋放它;而當 writers 不為 0 時,新讀者必須阻塞。
package rw;
public class ReaderWriter extends Thread {
String msg;
int NO;
final int N = 100;
static public int num = 0;
static public int readers = 0;
static public int writers = 0;
static Semaphore mutexr = new Semaphore(1);
static Semaphore mutexw = new Semaphore(1);
static Semaphore mutex = new Semaphore(1);
static Semaphore mutexWrite = new Semaphore(1);
static public String resource = "Last Writer:0";
public void read() {
if (writers != 0) // 有寫者則阻塞,後續讀者不許進來
mutex.P();
mutexr.P();
readers++;
if (readers == 1) // 讀時對寫互斥
mutexWrite.P();
mutexr.V();
System.out.println(" " + NO + " is reading, resource=" + resource);
mutexr.P();
readers--;
if (readers == 0)
mutexWrite.V();
mutexr.V();
if (writers != 0)
mutex.V();
}
public void write() {
mutexw.P();
writers++;
if (writers == 1)
mutex.P();
mutexw.V();
mutexWrite.P();
resource = "base" + NO;
System.out.println(NO + " IS WRITING, resource=" + resource);
mutexWrite.V();
mutexw.P();
writers--;
if (writers == 0)
mutex.V();
mutexw.V();
}
// run() 中按編號決定執行讀或寫,main() 啟動大量線程並把輸出重定向到文件
}
整份代碼通過 P/V 操作把讀者與寫者的准入規則嚴格串接起來,既保證同一時刻至多一個寫者,也讓多個讀者能並發,同時實現了寫者优先的語義。