线程同步之条件变量

《朱老师物联网大讲堂》学习笔记          
 学习地址: www.zhulaoshi.org
 
 
 
下面是老师课上示例代码,,
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>



char buf[200] = {0};
pthread_mutex_t mutex;
pthread_cond_t cond;
unsigned int flag = 0;


// 子线程程序,作用是统计buf中的字符个数并打印
void *func(void *arg)
{
	// 子线程首先应该有个循环
	// 循环中阻塞在等待主线程激活的时候,子线程被激活后就去获取buf中的字符
	// 长度,然后打印;完成后再次被阻塞
	
	//while (strncmp(buf, "end", 3) != 0)
	//sleep(1);
	while (flag == 0)
	{	
		pthread_mutex_lock(&mutex);
		pthread_cond_wait(&cond, &mutex);
		printf("本次输入了%d个字符\n", strlen(buf));
		memset(buf, 0, sizeof(buf));
		pthread_mutex_unlock(&mutex);
		//sleep(1);
	}
	
	
	pthread_exit(NULL);
}


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("pthread_create error.\n");
		exit(-1);
	}
	
	printf("输入一个字符串,以回车结束\n");
	while (1)
	{
		//pthread_mutex_lock(&mutex);
		scanf("%s", buf);
		pthread_cond_signal(&cond);
		//pthread_mutex_unlock(&mutex);
		// 去比较用户输入的是不是end,如果是则退出,如果不是则继续		
		if (!strncmp(buf, "end", 3))
		{
			printf("程序结束\n");
			flag = 1;
			
			//exit(0);
			break;
		}
		//sleep(1);
		// 主线程在收到用户收入的字符串,并且确认不是end后
		// 就去发信号激活子线程来计数。
		// 子线程被阻塞,主线程可以激活,这就是线程的同步问题。
		// 信号量就可以用来实现这个线程同步
	}

	
	// 回收子线程
	printf("等待回收子线程\n");
	ret = pthread_join(th, NULL);
	if (ret != 0)
	{
		printf("pthread_join error.\n");
		exit(-1);
	}
	printf("子线程回收成功\n");
	
	pthread_mutex_destroy(&mutex);
	pthread_cond_destroy(&cond);
	
	return 0;
}




强调一点的是,条件变量需要和互斥锁一起使用,
while (flag == 0)
{
  pthread_mutex_lock(&mutex);
  pthread_cond_wait(&cond, &mutex);
  printf("本次输入了%d个字符\n", strlen(buf));
  memset(buf, 0, sizeof(buf));
  pthread_mutex_unlock(&mutex);
  //sleep(1);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值