93_线程之条件变量

条件变量是线程之间通信所特有的,是效率比较高的

阻塞和唤醒是理解的要点

等待,条件满足了发过来,等待的往下执行

跟进程通信的异步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;
}







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值