线程中与互斥锁相关概念及API(2):条件变量相关API
1, 创建及销毁条件变量
int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);
int pthread_cond_destroy(pthread_cond_t cond);
除非需要创建一个非默认属性的条件变量,否则pthread_cont_init函数的attr参数可以设置为NULL。
2,等待
int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);
3,触发
int pthread_cond_signal(pthread_cond_t cond);
编程案例:
#include <stdio.h>
#include <pthread.h>
int g_data = 0;
pthread_mutex_t mutex;
pthread_cond_t cond; //定义条件
void *func1(void *arg)
{
printf("t1:%ld thread is creat\n",(unsigned long)pthread_self());
printf("t1:param is:%d\n",*((int *)arg));
while(1){
pthread_cond_wait(&cond,&mutex); //等待 signal触发才能运行
printf("t1 ======run\n");
printf("t1:%d\n",g_data);
sleep(1);
g_data = 0;
}
}
void *func2(void *arg)
{
printf("t2:%ld thread is creat\n",(unsigned long)pthread_self());
printf("t2:param is:%d\n",*((int *)arg));
while(1){
pthread_mutex_lock(&mutex);
printf("t2:%d\n",g_data);
pthread_mutex_unlock(&mutex);
g_data++;
if(g_data == 3){
pthread_cond_signal(&cond); //触发wait
printf("t2 ==== over\n");
}
sleep(1);
}
}
int main()
{
int param = 100;
pthread_t t1;
pthread_t t2;
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&cond,NULL); //初始化条件
int ret = pthread_create(&t1,NULL,func1,(void*)¶m);
if(ret == 0){
printf("pthread_creat success\n");
}
int ret2 = pthread_create(&t2,NULL,func2,(void*)¶m);
if(ret2 == 0){
printf("pthread_creat success\n");
}
printf("main:%ld\n",(unsigned long)pthread_self());
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond); //结束条件
return 0;
}
输出结果: