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