#include "stdio.h"
#include "pthread.h"
#include "stdlib.h"
#include "string.h"
struct test
 {
   int num;
   struct test *next;
 };
struct test *head;

pthread_cond_t ok=PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
void consume()
{
  struct test *mp;
  for(;;)
   {
     pthread_mutex_lock(&lock);
     if(head == NULL)
       {
          printf("Consum is waiting...\n");
          pthread_cond_wait(&ok,&lock);
          printf("Consum leave waiting %d\n",head->num);
       }
     printf("Consum get the number %d\n",head->num);
     mp=head;
     head=head->next;
     free(mp);
     pthread_mutex_unlock(&lock);
     sleep(rand()%5);
   }
}

void produce()
 {
  struct test *tmp;
  for(;;)
   {
   tmp=(struct test *)malloc(sizeof(struct test));
   tmp->num=rand()%1000+1;
   pthread_mutex_lock(&lock);
   tmp->next=head;
   head=tmp;
   printf("Produce %d\n",tmp->num);
   pthread_mutex_unlock(&lock);
   pthread_cond_signal(&ok);
   sleep(rand()%5);
   }
 }
int main()
 {
   pthread_t pid,cid;
   pthread_create(&pid,NULL,produce,NULL);
   pthread_create(&cid,NULL,consume,NULL);
   pthread_join(pid,NULL);
   pthread_join(cid,NULL);
   return 0;
 }