线程同步
2016-04-10 15:48
344 查看
一、线程同步
多个线程按照一定的顺序来执行,即为线程的同步。
二、线程同步实例
三、同步机制------条件变量
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;
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;
}
相关文章推荐
- JVM系列4:JVM总结
- 20145311 实验一 "Java开发环境的熟悉"
- 科技漫谈——无人机
- TCP/IP卷一(第二章学习)
- 详解网络流量监控
- JVM系列3:虚拟机类加载机制
- JVM系列2:垃圾收集器与内存分配策略
- Centos安装NodeJs 二进制文件方法
- 结对编程--四则运算
- POJ-2082 Terrible Sets (单调栈)
- 数据库的灵活操作
- Unable to get package info for [包路径]; is package not installed
- HDU 1253
- 消息队列通讯
- 多线程程序设计
- 如果时间不够 ,无法进行充分的测试怎么办?
- 由于没有详细了解Timestamp和Date之间的关系犯的错
- HDU 1159 && POJ 1458
- 20145227 《Java程序设计》第6周学习总结
- java中的接口和抽象类