条件变量是线程之间通信所特有的,是效率比较高的
阻塞和唤醒是理解的要点
等待,条件满足了发过来,等待的往下执行
跟进程通信的异步IO很相似
pthread_cond_init 初始化
pthread_cond_destroy 回收
pthread_cond_wait 等待
pthread_cond_signal/broardcast 只激活一个线程 激活多个线程
pthread_cond_t
示例代码:
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <pthread.h>
char buf[200] = {0};
pthread_mutex_t mutex;
pthread_cond_t cond;
void *func(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
if(!strncmp(buf, "end", 3))//注意此函数可以比较个数 “n”
{
break;//return 0或者exit(0)加头文件 此处都是可以的
}
printf("本次输入了%d个字符。\n", strlen(buf));//注意此函数用法
memset(buf, 0, sizeof(buf));
pthread_mutex_unlock(&mutex);
}
}
int main(void)
{
int ret = -1;
pthread_t th = -1;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
ret = pthread_create(&th, NULL, func, NULL);
if(ret < 0)
{
printf("pthred error.\n");
exit(-1);
}
printf("输入一个字符串,以回车结束。\n");
while(1)
{
scanf("%s", buf);//注意此函数的用法
if(!strncmp(buf, "end", 3))//注意此函数可以比较个数 “n”
{
printf("程序结束。\n");
pthread_cond_signal(&cond);
break;//return 0或者exit(0)加头文件 此处都是可以的
}
pthread_cond_signal(&cond);
}
//回收子线程
printf("等待回收子线程.\n");
pthread_join(th, NULL);
if(ret < 0)
{
printf("pthred error.\n");
exit(-1);
}
printf("回收子线程成功.\n");
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}