#include "stdio.h"
#include "pthread.h"
#include "stdlib.h"
int sum=0;
int head=0;
pthread_cond_t ok=PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;

void sum1()
 {
   pthread_mutex_lock(&lock);
   if(head != 1 )
     {
        printf("sum1 is waiting...\n");
        pthread_cond_wait(&ok,&lock);
     }
    printf("come from sum1: the sum is %d\n",sum);
    head++;
   int i=10;
   for(i=10;i<20;i++)
      sum+=i;
    printf("come from sum1 :the sum is %d\n",sum);
   pthread_mutex_unlock(&lock);
   sleep(rand()%5);
 }

void sum2()
 {
   pthread_mutex_lock(&lock);
   head++;
   int i=1;
   for(i=1;i<10;i++)
    {
       sum+=i;
    }
   printf("come from sum2 : the sum is %d\n",sum);
   pthread_mutex_unlock(&lock);
   pthread_cond_signal(&ok);
   sleep(rand()%5);
   pthread_mutex_lock(&lock);
   head++;
   for(i=20;i<30;i++)
      sum+=i;
   printf("come from sum2 : the sum is %d\n",sum);
   pthread_mutex_unlock(&lock);
   pthread_cond_signal(&ok);

 }

int main()
 {
   pthread_t pid,cid;
   pthread_create(&pid,NULL,sum1,NULL);
   pthread_create(&cid,NULL,sum2,NULL);
   pthread_join(pid,NULL);
   pthread_join(cid,NULL);
   return 0;
 }