- 流程
(1)生产者

(2)消费者

- 代码
#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++;
}
}
}