1. 程式人生 > >作業系統之程序同步問題

作業系統之程序同步問題

程序同步的兩種形式的制約關係
間接相互制約關係(程序互斥) 程序-程序
直接相互制約關係(程序同步) 程序-資源-程序
此處的資源一般指(臨界資源:在一段時間內只允許一個程序訪問的資源。臨界資源的訪問要求互斥的訪問。)

講到程序同步就不得不提生產者-消費者問題了,
int in=0,out=0;-----兩個指標,輸入輸出
item buffer[n];
semaphore mutex=1,empty=n,full=0;
利用互斥訊號量mutex,利用訊號量empty和full分別表示緩衝池空和緩衝池滿的數量
void producer(){ ----生產者
do{
producer an item nextp;

wait(empty); -----測量空間
wait(mutex); -----申請許可權
buffer[in]=nextp;
in=(in+1)%n;
signal(mutex);
signal(full);
}while(TURE);
}

void consumer(){
do{
wait(full);
wait(mutex);
nextc=buffer[out];
out=(out+1)%n;
signal(mutex);
signal(empty);
connsumer the item in nextc;

}while(TURE);
}

void main(){
cobegin
producer();consumer();
coend
}