条件变量:
当一个线程互斥的访问某个变量时,它可能会发现自己要完成某个操作需要某个共享变量达到条件。否则会进入阻塞。(就比如说,当前有个判断 : a = 0 ,线程1要执行1/a,需要的条件是a不等于0,现在线程1只能阻塞等待着a变量的改变。
这时需要通过线程2去改变共享变量a的值)
我们先看一下条件变量的API:
条件变量:
1.定义条件变量:pthread_cond_t cond;
2.初始化:pthread_cond_init(&cond,NULL)
3.等待条件 pthread_cond_wait(&cond,&mutex)
(1)mutex:如果没有在互斥环境,形同虚设
(2)如果在,wait函数将mutex置成1,wait返回后,将mutex恢复成原来值
4.修改条件 pthread_cond_signal(&cond)
5.销毁条件变量 pthread_cond_destroy(&cond)
我们可以看到等待条件变量的函数中有互斥量:
等待条件
pthread_cond_wait(&cond,&mutex)
(1)mutex:如果没有在互斥环境,形同虚设
(2)如果在,wait函数将mutex置成1,wait返回后,将mutex恢复成原来值
为什么会有互斥量呢?
条件变量的条件满足肯定牵扯到共享数据的修改,所以一定要加互斥锁来保护。没有互斥锁就无法安全的获取和修改共享数据。
设计模型应该如下:
pthread_mutex_lock()
while(条件不满足) //while是因为pthread_cond_wait可能是因为被信号打断而唤醒
pthread_cond_wait()
pthread_mutex_unlock()
pthread_mutex_lock()
pthread_cond_signal() //如果没有线程等待,信号被丢掉
pthread_mutex_unlock()
例子:
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<unistd.h>
#include<string.h>
pthread_cond_t cond;
pthread_mutex_t mutex;
void *rout1(void *arg)
{
while(1)
pthread_mutex_t mutex;
void *rout1(void *arg)
{
while(1)
{
pthread_cond_wait(&cond,&mutex);
printf("1 在运行 ...\n");
}
}
void *rout2(void *arg)
{
while(1)
{
pthread_cond_signal(&cond);
//printf("发出信号,告诉线程1条件满足!!\n");
sleep(4);
}
}
int main()
{
pthread_cond_init(&cond,NULL);
pthread_mutex_init(&mutex,NULL);
pthread_t tid1,tid2;
pthread_create(&tid1,NULL,rout1,NULL);
pthread_create(&tid2,NULL,rout2,NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
运行结果:
只有通过其他线程改变了条件,并发出了信号。在等待的线程条件满足,才能继续执行。