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