LINUX条件变量详解
一、条件变量概述
条件变量不是一个把锁,它实质上一个类似信号的东西,与锁相互配合使用,因为锁所能达到的功能就只有加锁和解锁,并不能实现线程之间的一些关联,于是条件变量就出现了,与锁相互配合使用。这与共享内存与信号量配合使用有些许相似之处。
1.1 函数API讲解
1.pthread_cond_init(),条件变量初始化
int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);
//函数参数一配置为初始化值的地址
//参数二用默认的方式初始化,restrict attr,一般配置为NULL
2.pthread_cond_init(),等待一个条件变量
int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);
//参数一:同上。
//参数二 :即为锁,这个锁用来解开唤醒这个条件变量的所控制的线程,可以解开这个锁,
3.pthread_cond_signal(),唤醒条件变量
int pthread_cond_signal(pthread_cond_t *cond);
4.pthread_cond_broadcast() ,唤醒所有条件变量
int pthread_cond_broadcast(pthread_cond_t *cond)
5.pthread_cond_destroy() ,销毁条件变量
int pthread_cond_destroy(pthread_cond_t *cond)
二、函数使用
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
int data = 0;
pthread_mutex_t mutex;
pthread_cond_t cond;
void *fun1(void *arg)
{
printf("xianchen1:the xiancheng num is%ld\n",(unsigned long)pthread_self());
printf("xianchen1:the parm is %d\n",*((int *)arg));
static int choose =0;
while(1)
{
pthread_cond_wait(&cond,&mutex);
printf("xianchen:the data is %d\n",++data);
printf("fun1 run!********************\n");
choose++;
if(choose==10)
{
exit(1);
}
data=0;
sleep(1);
}
}
void *fun2(void *arg)
{
printf("xianchen2:the xiancheng2 num is%ld\n",(unsigned long)pthread_self());
printf("xianchen2:the parm is %d\n",*((int *)arg));
while(1)
{
pthread_mutex_lock(&mutex);
printf("xianchen2:the data is %d\n",++data);
if(data==4){
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main()
{
pthread_t t1;//变量
pthread_t t2;//变量
int gram = 100;//传递的一个值
//int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
pthread_mutex_init(&mutex,NULL);//初始化锁
pthread_cond_init(&cond,NULL);//初始化条件变量
ret = pthread_create(&t1,NULL,fun1,(void *)&gram);//创建线程
ret2 = pthread_create(&t2,NULL,fun2,(void *)&gram);//创建线程
pthread_join(t1,NULL);//等待线程退出
pthread_join(t2,NULL);//等待线程退出
pthread_mutex_destroy(&mutex);//销毁互斥锁
pthread_cond_destroy(&cond);//销毁条件变量
return 0;
}
三、结果展示与分析
通过代码我们可以看到,这个对于data的访问一定格式线程2先访问完之后,再唤醒线程1去对公共变量data的访问控制,实现的比较灵活,在实际工作中具有重要意义。(这里我写的一个测试脚本,./a.out 2 >> test.ret.txt &,可以在文件中输出结果),若有助于大家学习,点小个赞吧!