1.生產者消費者問題
一個消費者一個生產者時
semaphore full , empty;
empty = n , full = 0;
int in = 0 , out = 0;
cobegin
process producer () { process consumer () {
while(true){ while(true){
produce(); P(full);
P(empty); out = (out+1)%n;
in = (in+1)%n; V(empty);
V(full); comsumer();
} }
} }
coend
而一組消費者,一組生產者時,不僅生產者與消費者之間要同步,而且各個生產者之間、各個消費者之間還必須互斥地訪問緩沖區。
所以要多一個互斥的信號mutex
semaphore full , empty , mutex;
empty = n , full = 0 , mutex = 1;
int in = 0 , out = 0;
cobegin
process producer () { process consumer () {
while(true){ while(true){
produce(); P(full);
P(empty); P(mutex) ;
P(mutex) ; out = (out+1)%n;
in = (in+1)%n; V(mutex) ;
V(mutex) ; V(empty);
V(full); comsumer();
} }
} }
coend