#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <error.h>
#include <semaphore.h>
int num=0;
sem_t sem1,sem2;
void thread1(void)
{
int n,i;
while(1)
{
sem_wait(&sem1);
while(num>=0 && num<=5)
{
if(num>=5)
{
printf("生产数量已达最大,必须消费\n");
}
else
{
n=rand()%(6-num);
for(i=0;i<n;i++)
{
num++;
printf("生产中----->剩余%d\n",num);
sleep(1);
}
}
sem_post(&sem2);
break;
}
}
pthread_exit(NULL);
}
void thread2(void)
{
char c[2];int n,i;
while(1)
{
sem_wait(&sem2);
while(num>=0 && num<=5)
{
if(num<=0)
{
printf("没有任何产品,必须生产\n");
}
else
{
n=rand()%(num+1);
for(i=0;i<n;i++)
{
num--;
printf("消费中----->剩余%d\n",num);
sleep(1);
}
}
sem_post(&sem1);
break;
}
}
pthread_exit(NULL);
}
int main()
{
pthread_t id1,id2;
srand(time(NULL));
int ret;
sem_init(&sem1,0,1);
sem_init(&sem2,0,0);
ret=pthread_create(&id1,NULL,(void *)thread1,NULL);
if(ret!=0)
{
perror("create pthread error");
exit(1);
}
ret=pthread_create(&id2,NULL,(void *)thread2,NULL);
if(ret!=0)
{
perror("create pthread error");
exit(1);
}
pthread_join(id1,NULL);
pthread_join(id2,NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
}