标签:include break void 休息 strong his int str 结束
概念:多个线程按照规定的顺序来执行,即为线程同步
扫地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);
}
标签:include break void 休息 strong his int str 结束
原文地址:http://www.cnblogs.com/1932238825qq/p/7373166.html