多线程同步

来源:互联网 发布:网络语红烧肉什么意思 编辑:程序博客网 时间:2024/06/08 09:59

1.多个线程按照规定的顺序来执行,即线程同步

2.条件变量实现线程同步

 初始化:      pthread_cond_t cond_ready = PTHREAD_COND_INITIALIZER; 等待条件成熟:pthread_cond_wait(&cond_ready,&mut); 设置成熟条件:pthread_cond_signal(&cond_ready);

3.综合实例

/*********************************************************************** * file_name:   sync.c * Description: A先扫完5次地后B拖一次地 ***********************************************************************/#include <stdio.h>#include <pthread.h>pthread_t thread[2];int number = 0;pthread_mutex_t mut;pthread_cond_t cond_ready =  PTHREAD_COND_INITIALIZER;void studentA(){int i;for(i=0; i<5; i++){pthread_mutex_lock(&mut);//扫一次地number++;if(number>=5){printf("student A has finished his work !\n");//通知B同学pthread_cond_signal(&cond_ready);}pthread_mutex_unlock(&mut);//休息1秒钟sleep(1);}//退出pthread_exit(NULL);}void studentB(){pthread_mutex_lock(&mut);if(number<5){//等待A的唤醒,此函数会自动上锁pthread_cond_wait(&cond_ready,&mut);}number = 0;pthread_mutex_unlock(&mut);printf("student B has finished his work !\n");//退出pthread_exit(NULL);}int main(){//初始化互斥锁pthread_mutex_init(&mut,NULL);//创建A同学线程pthread_create(&thread[0],NULL,studentA,NULL);//创建B同学线程pthread_create(&thread[1],NULL,studentB,NULL);//等待A同学线程结束pthread_join(thread[0],NULL);//等待B同学线程结束pthread_join(thread[1],NULL);}


0 0
原创粉丝点击