- 流程
(1)生产者
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7e1ab33589d686e2d4b41fa2d6566dad.png)
(2)消费者
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ce82b4fd4a1ce01a49bc821a843009bc.png)
- 代码
#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++;
}
}
}