概念
条件变量是线程另一可用的同步机制。条件变量给多个线程提供了一个会合的场所。条件变量与互斥量一起使用时,允许线程以无竞争的方式等待特定的条件发生。
用法
第一步全局定义一个pthread_cond_t类型
pthread_cond_t cond;
第二步在主函数创建及销毁条件变量
#include <pthread.h>
int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);
int pthread_cond_destroy(pthread_cond_t cond);
// 返回:若成功返回0,否则返回错误编号
第三步线程等待
int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);
或者
int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, cond struct timespec *restrict timeout);
第四步另一个线程触发线程等待运行
int pthread_cond_signal(pthread_cond_t cond);
或者
int pthread_cond_broadcast(pthread_cond_t cond);
例子:
fun1检测等待pthread_cond_wait
fun2计数到达3时使用pthread_cond_signal
触发退出动作
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
int data = 0;
pthread_mutex_t mutex;
pthread_cond_t cond;
void *fun1(void *arg){
printf("t1: %ld thread\n",(unsigned long)pthread_self());//将其id输出
printf("param1 : %d\n",*((int *)arg));
pthread_mutex_lock(&mutex);
while(1){
pthread_cond_wait(&cond,&mutex);
printf("=====t1 run======\n");
printf("t1: %d\n",data);
printf("=====t1 quit======\n");
pthread_mutex_unlock(&mutex);
exit(0);
}
}
void *fun2(void *arg){
printf("t2: %ld thread\n",(unsigned long)pthread_self());//将其id输出
printf("param2 : %d\n",*((int *)arg));
while(1){
pthread_mutex_lock(&mutex);
printf("t2: %d\n",data++);
if(data == 3){
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main(){
int ret;
int param = 100;
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&cond,NULL);
pthread_t t1;
pthread_t t2;
char *pret = NULL;
ret = pthread_create(&t1,NULL,fun1,(void *)¶m);//创建线程
ret = pthread_create(&t2,NULL,fun2,(void *)¶m);
printf("main: %ld thread\n",(unsigned long)pthread_self());
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}