pthread_cond_write

来源:互联网 发布:电脑软件删不掉怎么办 编辑:程序博客网 时间:2024/06/11 19:32
  1. 1 #include<pthread.h>   
  2.   2 #include<unistd.h>   
  3.   3 #include<stdio.h>   
  4.   4 #include<stdlib.h>   
  5.   5    
  6.   6 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;/*初始化互斥锁*/  
  7.   7 pthread_cond_t  cond = PTHREAD_COND_INITIALIZER;//init cond  
  8.   8    
  9.   9 void *thread1(void*);   
  10.  10 void *thread2(void*);   
  11.  11    
  12.  12 int i = 1; //global  
  13.  13    
  14.  14 int main(void){   
  15.  15     pthread_t t_a;   
  16.  16     pthread_t t_b;//two thread  
  17.  17    
  18.  18     pthread_create(&t_a,NULL,thread2,(void*)NULL);   
  19.  19     pthread_create(&t_b,NULL,thread1,(void*)NULL);//Create thread  
  20.  20    
  21.  21     pthread_join(t_b,NULL);//wait a_b thread end  
  22.  22     pthread_mutex_destroy(&mutex);   
  23.  23     pthread_cond_destroy(&cond);   
  24. 24     exit(0);   
  25.  25 }   
  26.  26    
  27.  27 void *thread1(void *junk){   
  28.  28     for(i = 1;i<= 9; i++){   
  29.  29         pthread_mutex_lock(&mutex); //互斥锁  
  30.  30         printf("call thread1 \n");   
  31.  31         if(i%3 == 0)   
  32.  32             pthread_cond_signal(&cond); //send sianal to t_b  
  33.  33         else  
  34.  34             printf("thread1: %d\n",i);   
  35.  35         pthread_mutex_unlock(&mutex);   
  36.  36         sleep(1);   
  37.  37     }   
  38.  38 }   
  39.  39    
  40.  40 void *thread2(void*junk){   
  41.  41     while(i < 9)   
  42.  42     {   
  43.  43         pthread_mutex_lock(&mutex);   
  44.  44         printf("call thread2 \n");   
  45.  45         if(i%3 != 0)   
  46.  46             pthread_cond_wait(&cond,&mutex); //wait  
  47.   47         printf("thread2: %d\n",i);   
  48.  48         pthread_mutex_unlock(&mutex);   
  49.  49         sleep(1);   
  50.  50     }   
  51.  51 }