Linux多线程之线程同步(条件变量)

什么是线程同步?

在这里插入图片描述
案例原型:A先扫5次地,A扫完地B再拖地,从而完成线程同步。

#include <stdio.h>
#include <pthread.h>


pthread_t thread[2];

int number = 0;//共享资源

pthread_mutex_t mut;

void studentA()
{
	int i;
	for(i=0;i<5;i++)
	{
		pthread_mutex_lock(&mut);//上锁
		
		//扫1次地
		number++;
		
		if(number >= 5)
			printf("student A has finish his work!\n");
		
		pthread_mutex_unlock(&mut);//解锁
		
		//休息1s钟
		sleep(1);

	}
	
	//退出
	pthread_exit(NULL);

}

void studentB()
{
	while(1)
	{		
		pthread_mutex_lock(&mut);
		
		if(number >= 5)//判断A同学是否已经扫完5次地
		{
			//拖地
			number = 0;
			
			pthread_mutex_unlock(&mut);
			
			printf("student B has finish his work!\n");
			
			break;
		}
		else
		{
			pthread_mutex_unlock(&mut);
						
			//睡眠2s钟
			sleep(2);
		}					
		
	}
	
	//退出
	pthread_exit(NULL);
	
}

int main()
{
	//初始化互斥锁
	pthread_mutex_init(&mut,NULL);
	
	//创建A同学线程
	pthread_create(&thread[0], NULL, studentA,  NULL);
	
	//创建B同学线程
	pthread_create(&thread[1], NULL, studentB,  NULL);

	
	//等待A同学线程结束
	pthread_join(thread[0], NULL);

	
	//等待B同学线程结束
	pthread_join(thread[1], NULL);

	
}

运行结果:

在这里插入图片描述
结果如我们所愿,A先完成工作,B再完成工,实现了线程之间的同步。但是有没有缺点那?明显有缺点,B同学需要每隔2s检查一次,判断number是否>5,这个过程是非常浪费cpu、低效的!!!那么有没有更加高效的办法哪?

条件变量:

在这里插入图片描述
在这里插入图片描述

#include <stdio.h>
#include <pthread.h>


pthread_t thread[2];

int number = 0;//共享资源

pthread_mutex_t mut;

pthread_cond_t cond_ready=PTHREAD_COND_INITIALIZER; //条件变量---初始化

void studentA()
{
	int i;
	for(i=0;i<5;i++)
	{
		pthread_mutex_lock(&mut);//上锁
		
		//扫1次地
		number++;
		
		if(number >= 5)
		{
			printf("student A has finish his work!\n");
			
			//条件变量---通知B同学
			pthread_cond_signal(&cond_ready);
		}
		
		pthread_mutex_unlock(&mut);//解锁
		
		//休息1s钟
		sleep(1);

	}
	
	//退出
	pthread_exit(NULL);

}

void studentB()
{	
	pthread_mutex_lock(&mut);//加锁
	
	if(number < 5)
	{		
		//条件变量---等待
		pthread_cond_wait(&cond_ready, &mut);//条件变量一般和互斥锁mutex一起使用
										  //条件不满足时,会把mutex先unlock,再重新lock
	}
	
	//拖地
	number=0;
	
	pthread_mutex_unlock(&mut);//解锁
	printf("student B has finish his work\n");
				
	
	//退出
	pthread_exit(NULL);
	
}

int main()
{
	//初始化互斥锁
	pthread_mutex_init(&mut,NULL);
	
	//创建A同学线程
	pthread_create(&thread[0], NULL, studentA,  NULL);
	
	//创建B同学线程
	pthread_create(&thread[1], NULL, studentB,  NULL);

	
	//等待A同学线程结束
	pthread_join(thread[0], NULL);

	
	//等待B同学线程结束
	pthread_join(thread[1], NULL);

	
}

运行结果:

在这里插入图片描述

疑问?

为什么pthread_cond_wait(&cond_ready, &mut);函数第二个参数需要互斥锁?

https://baike.baidu.com/item/pthread_cond_wait/3011997?fr=aladdin

https://www.cnblogs.com/secondtonone1/p/5580203.html

猜你喜欢

转载自blog.csdn.net/QQ1402369668/article/details/87119188