- 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;//init cond
- 8
- 9 void *thread1(void*);
- 10 void *thread2(void*);
- 11
- 12 int i = 1; //global
- 13
- 14 int main(void){
- 15 pthread_t t_a;
- 16 pthread_t t_b;//two thread
- 17
- 18 pthread_create(&t_a,NULL,thread2,(void*)NULL);
- 19 pthread_create(&t_b,NULL,thread1,(void*)NULL);//Create thread
- 20
- 21 pthread_join(t_b,NULL);//wait a_b thread end
- 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); //send sianal to t_b
- 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); //wait
- 47 printf("thread2: %d\n",i);
- 48 pthread_mutex_unlock(&mutex);
- 49 sleep(1);
- 50 }
- 51 }
pthread_cond_write
最新推荐文章于 2024-03-20 17:51:29 发布