您的位置:首页 > 其它

线程同步

2016-04-10 15:48 344 查看
一、线程同步

多个线程按照一定的顺序来执行,即为线程的同步。



二、线程同步实例

#include<pthread.h>
#include<unistd.h>
#include<stdio.h>
pthread_tthread[2];
pthread_mutex_tmux;
intnumber=0;
void*StudentA()
{
inti=0;
for(i=0;i<5;i++)
{
//扫一次
pthread_mutex_lock(&mux);
number++;
if(number>=5)
printf("studentAhasfinishedhiswork\n");
pthread_mutex_unlock(&mux);
sleep(1);
}
pthread_exit(NULL);
}
void*StudentB()
{
while(1)
{
//判断A同学是否已经扫完5次地
pthread_mutex_lock(&mux);
if(number>=5)
{
number=0;
//拖地
printf("StudentBhasfinishedhiswork\n");
pthread_mutex_unlock(&mux);
break;
}
else
{
pthread_mutex_unlock(&mux);
sleep(2);
}
}
pthread_exit(NULL);
}
intmain()
{
//初始化互斥锁
pthread_mutex_init(&mux,NULL);
//1,创建A同学线程
pthread_create(&thread[0],NULL,StudentA,NULL);
//2.创建B同学线程
pthread_create(&thread[1],NULL,StudentB,NULL);
//3.等待A同学线程结束
pthread_join(thread[0],NULL);
//4.等待B同学线程结束
pthread_join(thread[1],NULL);
return0;
}


三、同步机制------条件变量

1.初始化

pthread_cond_tcond_ready=PTHREAD_COND_INITIALIZER

2.等待成熟条件

pthread_cond_wait(&cond_ready,&mut)

3.设置成熟调剂

pthread_cond_signal(&cond_ready)

#include<pthread.h>
#include<unistd.h>
#include<stdio.h>
pthread_tthread[2];
pthread_mutex_tmux;
intnumber=0;
pthread_cond_tcond_ready=PTHREAD_COND_INITIALIZER;
void*StudentA()
{
inti=0;
for(i=0;i<5;i++)
{
//扫一次
pthread_mutex_lock(&mux);
number++;
if(number>=5)
{
//printf("studentAhasfinishedhiswork\n");
/*通知B同学*/
pthread_cond_signal(&cond_ready);
pthread_mutex_unlock(&mux);
sleep(1);
}
}
pthread_exit(NULL);
}
void*StudentB()
{
pthread_mutex_lock(&mux);
if(number<5)
{
pthread_cond_wait(&cond_ready,&mux);
}
number=0;
pthread_mutex_unlock(&mux);
printf("studenthasfinishedhiswork\n");
pthread_exit(NULL);
}
intmain()
{
//初始化互斥锁
pthread_mutex_init(&mux,NULL);
//1,创建A同学线程
pthread_create(&thread[0],NULL,StudentA,NULL);
//2.创建B同学线程
pthread_create(&thread[1],NULL,StudentB,NULL);
//3.等待A同学线程结束
pthread_join(thread[0],NULL);
//4.等待B同学线程结束
pthread_join(thread[1],NULL);
return0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: