一、什么是同步
多个线程按照规定的顺序来执行,即为线程同步。
1.1线程同步方式一
通过互斥锁的方式实现线程同步,可以实现但是执行效率比较低(sync.c)
1 #include <stdio.h> 2 #include <pthread.h> 3 #include <string.h> 4 5 6 pthread_t thread[2]; 7 int number = 0; 8 pthread_mutex_t mut; 9 10 11 void studentA() 12 { 13 int i; 14 for(i=0;i<5;i++) 15 { 16 pthread_mutex_lock(&mut); 17 //扫地 18 number++; 19 if( number>=5 ) 20 printf("student A has finish his work! \n"); 21 22 pthread_mutex_unlock(&mut); 23 //休息1秒钟 24 sleep(1); 25 } 26 //退出 27 pthread_exit(NULL); 28 } 29 30 void studentB() 31 { 32 while(1) 33 { 34 pthread_mutex_lock(&mut); 35 if(number>=5) //判断A同学是否已经扫完5次地 36 { 37 //执行拖地 38 number = 0; 39 printf("student B has finish his work \n"); 40 41 pthread_mutex_unlock(&mut); 42 //退出 43 break; 44 } 45 else 46 { 47 pthread_mutex_unlock(&mut); 48 //睡眠2秒钟 49 sleep(2); 50 } 51 } 52 pthread_exit(NULL); //退出 53 } 54 55 int main() 56 { 57 //初始化互斥锁 58 pthread_mutex_init(&mut,NULL); 59 60 //创建A同学线程 61 pthread_create(&thread[0],NULL,studentA,NULL); 62 63 //创建B同学线程 64 pthread_create(&thread[1],NULL,studentB,NULL); 65 66 //等待A同学线程结束 67 pthread_join(thread[0],NULL); 68 69 //等待B同学线程结束 70 pthread_join(thread[1],NULL); 71 72 return 0; 73 }
1.2线程同步方式二
使用条件变量,可以使CPU利用率提高(sync1.c)
1 #include <stdio.h> 2 #include <pthread.h> 3 #include <string.h> 4 5 6 pthread_t thread[2]; 7 int number = 0; 8 pthread_mutex_t mut; 9 pthread_cond_t cond_ready=PTHREAD_COND_INITIALIZER; 10 11 void studentA() 12 { 13 int i; 14 for(i=0;i<5;i++) 15 { 16 pthread_mutex_lock(&mut); 17 //扫地 18 number++; 19 if( number>=5 ) 20 { 21 printf("student A has finish his work! \n"); 22 23 //通知B同学 24 pthread_cond_signal(&cond_ready); 25 } 26 pthread_mutex_unlock(&mut); 27 //休息1秒钟 28 sleep(1); 29 } 30 //退出 31 pthread_exit(NULL); 32 } 33 34 void studentB() 35 { 36 37 pthread_mutex_lock(&mut); 38 if(number<5) 39 pthread_cond_wait(&cond_ready, &mut); 40 number = 0; 41 pthread_mutex_unlock(&mut); 42 printf("student B has finish his work! \n"); 43 44 pthread_exit(NULL); //退出 45 } 46 47 int main() 48 { 49 //初始化互斥锁 50 pthread_mutex_init(&mut,NULL); 51 52 //创建A同学线程 53 pthread_create(&thread[0],NULL,studentA,NULL); 54 55 //创建B同学线程 56 pthread_create(&thread[1],NULL,studentB,NULL); 57 58 //等待A同学线程结束 59 pthread_join(thread[0],NULL); 60 61 //等待B同学线程结束 62 pthread_join(thread[1],NULL); 63 64 return 0; 65 }
1.3条件变量
初始化:
pthread_cond_t cond_ready=PTHREAD_COND_INITIALIZER;
等待条件成熟:
pthread_cond_wait(&cond_ready, &mut);
设置条件成熟:
pthread_cond_signal(&cond_ready);
时间: 2024-12-24 14:12:28