- 流程
(1)生产者
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190409162105572.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JyeWFudF94dw==,size_16,color_FFFFFF,t_70)
(2)消费者
![在这里插入图片描述](https://img-blog.csdnimg.cn/2019040916214570.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JyeWFudF94dw==,size_16,color_FFFFFF,t_70)
- 代码
#define N 20
typedef int semaphore;
int buf[N] = {0};
int in = 0;
int out = 0;
int productID = 0;
semaphore mutex = 1;
semaphore proCmutex = 1;
int empty = N;
int full = 0;
void produce()
{
while(1)
{
if(empty <= 0)
{
printf("缓冲区已满\n");
sleep(2000);
}
else
{
while(mutex <= 0);
mutex--;
productID++;
printf("生产1个产品,ID是%d,缓冲区位置%d\n",productID,in);
empty--;
in = (in+1)%N;
mutex++;
full++;
}
}
}
void consume()
{
while(1)
{
if(full <= 0)
{
printf("缓冲区已空\n", );
sleep(2000);
}
else
{
while(mutex <= 0);
mutex--;
int ppid = buf[out];
buf[out] = 0;
printf("\t\t\t\t消耗1个产品,ID是%d,缓冲区位置%d\n",ppid,out);
out = (out+1)%N;
mutex++;
empty++;
}
}
}