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);
}