],in);
in=(in+1)%10;
v(&s);
v(&full);
}
}
consumer()
{
int out=0;
while(1)
{
delay(400);
p(&full);
p(&s);
printf("Consumer: There are %d products in NO.%d buffer\n",--product[out],out);
out=(out+1)%10;
v(&s);
v(&empty);
}
}
main()
{
set(&s,1);
set(&empty,20);
set(&full,0);
cobegin(producer,consumer,0);
getch();
}
(3)一组生产者、一组消费者,公用n个环形缓冲区
因为有多个生产者和多个消费者,生产者之间存在互斥关系,消费者之间也存在互斥关系。所以我们要用信号量来控制一个时间只能有一个生产者在生产,一个消费者在消费。所以我们设mutex1为生产者之间的互斥信号量,初值为1,mutex2为消费者之间的互斥信号量,初值为2.,
程序如下:
#include
semaphore s,empty,full,mutex1,mutex2;
int product[10]={0};
producer()
{
int in=0;
while(1)
{
delay(20);
p(&empty);
p(&mutex1);
p(&s);
printf("Producer: There are %d products in NO.%d buffer\n",++product[in],in);
in=(in+1)%10;
v(&s);
v(&mutex1);
v(&full);
}
}
consumer()
{
int out=0;
while(1)
{
delay(400);
p(&full);
p(&mutex2);
p(&s);
printf("Consumer: There are %d products in NO.%d buffer\n",--product[out],out);
out=(out+1)%10;
v(&s);
v(&mutex2);
v(&empty);
}
}
main()
{
set(&s,1);
set(&empty,20);
set(&full,0);
set(&mutex1,1);
set(&mutex2,1);
cobegin(producer,consumer,0);
getch();
}