线程同步
使用条件变量同步线程
初始化
pthread_cond_t cond_ready = PTHREAD_COND_INITIALIZER;
等待条件成熟
Pthread_cond_wait(&cond_ready,&mut);
设置条件成熟
Pthread_cond_signal(&cond_ready);
没有使用条件变量同步线程例程:缺点:cpu使用效率低
pthread_sync.c
1 #include <stdio.h> 2 #include <pthread.h> 3 4 pthread_t thread[2]; 5 int number = 0; 6 pthread_mutex_t mut; 7 8 void studentA() 9 { 10 int i; 11 for(i = 0;i < 5;i++) 12 { 13 pthread_mutex_lock(&mut); 14 //扫一次地 15 number++; 16 if(number >=5) 17 { 18 printf("student A has finish his work!\n"); 19 } 20 pthread_mutex_unlock(&mut); 21 //休息一秒钟 22 sleep(1); 23 } 24 pthread_exit(NULL); 25 } 26 27 void studentB() 28 { 29 while(1) 30 { 31 pthread_mutex_lock(&mut); 32 if(number >= 5)//判断A同学是否已经扫完5次地 33 { 34 //拖地 35 number = 0; 36 pthread_mutex_unlock(&mut); 37 printf("student B has finish his work!\n"); 38 break; 39 } 40 else 41 { 42 pthread_mutex_unlock(&mut); 43 //睡眠2秒钟 44 sleep(2); 45 } 46 } 47 //退出 48 pthread_exit(NULL); 49 } 50 51 int main() 52 { 53 //初始化互斥锁 54 pthread_mutex_init(&mut,NULL); 55 //创建A同学线程 56 pthread_create(&thread[0],NULL,studentA,NULL); 57 //创建B同学线程 58 pthread_create(&thread[1],NULL,studentB,NULL); 59 //等待A同学线程结束 60 pthread_join(pthread[0],NULL); 61 //等待B同学线程结束 62 pthread_jion(pthread[1],NULL); 63 64 return 0; 65 }
pthread_sync.c
使用条件变量来线程同步:
pthread_sync.c
1 #include <stdio.h> 2 #include <pthread.h> 3 4 pthread_t thread[2]; 5 int number = 0; 6 pthread_mutex_t mut; 7 pthread_cond_t cond_read = PTHREAD_COND_INITIALIZER; 8 9 void studentA() 10 { 11 int i; 12 for(i = 0;i < 5;i++) 13 { 14 pthread_mutex_lock(&mut); 15 //扫一次地 16 number++; 17 if(number >=5) 18 { 19 printf("student A has finish his work!\n"); 20 pthread_cond_signal(&cond_ready); 21 } 22 pthread_mutex_unlock(&mut); 23 //休息一秒钟 24 sleep(1); 25 } 26 pthread_exit(NULL); 27 } 28 29 void studentB() 30 { 31 pthread_mutex_lock(&mut);//先上锁 32 if(number < 5) 33 { 34 pthread_cond_wait(&cond_ready,&mut);//如果没有到5次的话先解锁互斥量,再上锁 35 } 36 number = 0; 37 pthread_mutex_unlock(&mut); 38 printf("student B has finish his work!\n"); 39 //退出 40 pthread_exit(NULL); 41 } 42 43 int main() 44 { 45 //初始化互斥锁 46 pthread_mutex_init(&mut,NULL); 47 //创建A同学线程 48 pthread_create(&thread[0],NULL,studentA,NULL); 49 //创建B同学线程 50 pthread_create(&thread[1],NULL,studentB,NULL); 51 //等待A同学线程结束 52 pthread_join(pthread[0],NULL); 53 //等待B同学线程结束 54 pthread_jion(pthread[1],NULL); 55 56 return 0; 57 }
pthread_sync.c
时间: 2024-10-12 21:45:47