//#include < stdio.h>
//#include < semaphore.h>
//#include < pthread.h>
//#include < stdlib.h>
sem_t full;
sem_t empty;
int num = 0;
char buf[BUFSIZ];
void * producer(void)
{
while(1)
{
sem_wait(&full);
num++;
printf(“produce:”);
scanf(“%s”,buf);
if(strcmp(buf,”quit”) == 0)
{
exit(1);
}
printf(“product:%d\n”,num);
sem_post(&empty);
}
}
void * consumer(void)
{
while(1)
{
sem_wait(&empty);
num–;
printf(“consume:%s\n”,buf);
printf(“product:%d\n”,num);
sem_post(&full);
}
}
int main()
{
int ret = 0;
pthread_t id1,id2;
sem_init(&full,0,1);
sem_init(&empty,0,0);
ret = pthread_create(&id1,NULL,(void *)producer,NULL);
if(ret)
{
printf("creat pthread1 failed!\n");
}
ret = pthread_create(&id2,NULL,(void *)consumer,NULL);
if(ret)
{
printf("creat pthread2 failed!\n");
}
pthread_join(id1,NULL);
pthread_join(id2,NULL);
sem_destroy(&full);
sem_destroy(&empty);
return 0;
}