首页 > 编程语言 > 详细

多线程同步

时间:2017-08-16 14:28:47      阅读:190      评论:0      收藏:0      [点我收藏+]

概念:多个线程按照规定的顺序来执行,即为线程同步

扫地5次后拖地模型

#include<pthread.h>
#include<stdio.h>

pthread_mutex_t mut;
pthread_t thread[2];
int number=0;

void studentA()
{
int i;

for(i=0;i<5;i++)
{
//扫地1次
pthread_mutex_lock(&mut); //使用前保护起来
number++;
if(number>=5)
printf("studentA has finished his work\n");

//休息1秒
pthread_mutex_unlock(&mut); //使用后解开
sleep(1);

}

//扫地5次,退出
pthread_exit(NULL);
}


void studentB()
{

while(1)

{
//判断A是否扫地5次了
pthread_mutex_lock(&mut); //使用前保护起来

if(number>=5)
{
//拖地
number=0;
pthread_mutex_unlock(&mut); //使用后解开
printf("studentB has finished his work\n");
break;
}

else
{
//睡2秒
sleep(2);
}
}
//退出
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);

}

多线程同步

原文:http://www.cnblogs.com/1932238825qq/p/7373166.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!