一、什么是条件变量
条件变量是线程另一可用的同步机制。条件变量给多个线程提供了一个会合的场所。条件变量与互斥量一起使用时,允许线程以无竞争的方式等待特定的条件发生。
二、条件变量API
1.创建条件变量
#include <pthread.h>
int pthread_cond_init(pthread_cond_t *restrict cond,
const pthread_condattr_t *restrict attr);
参数:
pthread_cond_t *restrict cond: 条件变量的地址
const pthread_condattr_t *restrict attr: 条件变量的属性,默认写NULL
返回值:若成功返回0,否则返回错误编号
//方法一(动态初始化):pthread_cond_t cond;
//方法二(静态初始化):pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
//如果用第二种方法,就不用在main函数里写pthread_cond_init()了
2.销毁条件变量
#include <pthread.h>
int pthread_cond_destroy(pthread_cond_t cond);
参数:pthread_cond_t cond: 条件变量的地址
返回值:若成功返回0,否则返回错误编号
3.等待条件变量
#include <pthread.h>
int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);
参数:
pthread_cond_t *restrict cond: 条件变量的地址
pthread_mutex_t *restrict mutex: 互斥锁的地址
返回值:若成功返回0,否则返回错误编号
4.触发条件变量
#include <pthread.h>
int pthread_cond_signal(pthread_cond_t cond); 函数将唤醒等待该条件的某个线程
参数:pthread_cond_t cond: 条件变量的地址
返回值:若成功返回0,否则返回错误编号
5.广播条件变量
#include <pthread.h>
int pthread_cond_broadcast(pthread_cond_t cond); 函数将唤醒等待该条件的所有进程
参数:pthread_cond_t cond: 条件变量的地址
返回值:若成功返回0,否则返回错误编号
三、编程示例
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
int g_data = 0;
pthread_mutex_t mutex;
pthread_cond_t cond;
void *func1(void *arg)
{
printf("t1:%ld thread is create\n",(unsigned long)pthread_self());
printf("t1:param is %d\n",*((int *)arg));
static int cnt = 0;
while(1){
pthread_cond_wait(&cond,&mutex);//等待条件变量
printf("t1 run===============================\n");
printf("t1:%d\n",g_data);
g_data = 0;
sleep(1);
}
}
void *func2(void *arg)
{
printf("t2:%ld thread is create\n",(unsigned long)pthread_self());
printf("t2:param is %d\n",*((int *)arg));
while(1){
printf("t2:%d\n",g_data);
pthread_mutex_lock(&mutex);//加锁
g_data++;
pthread_mutex_unlock(&mutex);//解锁
if(g_data == 3){
pthread_cond_signal(&cond);//唤醒线程1
}
sleep(1);
}
}
int main()
{
int ret;
int param = 100;
pthread_t t1;
pthread_t t2;
pthread_mutex_init(&mutex,NULL);//创建锁
pthread_cond_init(&cond,NULL);//创建条件变量
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_mutex_destroy(&mutex);//销毁锁
pthread_cond_destroy(&cond);//销毁条件变量
return 0;
}
Notes:测试条件变量小妙招
1.新建一个test.c文件
#include <stdio.h>
int main(int argc,char **argv){
int i=0;
int time = atoi(argv[1]);
for(i=0;i<time;i++){
system("./demo8");
}
return 0;
}
2.让test.c文件,去执行demo8的程序,然后把执行出来的结果打印到另一个文件中。
demo8程序是怎么来的:gcc demo8.c -lpthread -o demo8
执行命令:./a.out 10>>test.ret.txt &
其中,>> 指追加的意思
& 取地址,意思是在后台运行
test.ret.txt 指另外一个文件
3.打开test.ret.txt,测试结果显示