条件变量、生产者消费者模型

本文详细讲解了生产者消费者模型中,如何利用条件变量与互斥锁的配合,实现线程间的同步与阻塞。通过实例展示了如何使用`pthread_cond_t`和`pthread_mutex_t`来管理资源,确保在生产者产生数据后,消费者能够正确消费。
摘要由CSDN通过智能技术生成

与互斥锁不同,条件变量是用来等待而不是用来上锁的,条件变量本身不是锁!

条件变量用来自动阻塞一个线程,直到某特殊情况发生为止。通常条件变量和互斥锁同时使用。

条件变量的两个动作:

  1. 条件不满, 阻塞线程
  2. 当条件满足, 通知阻塞的线程开始工作

条件变量的类型: pthread_cond_t。

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
生产者消费者模型:
在这里插入图片描述

#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>

//链表结点
typedef struct _node_t
{
	int data;
	struct _node_t* next;
}node_t;

node_t* head=NULL;//头节点
//条件变量
pthread_cond_t cond;
//互斥量
pthread_mutex_t mutex;

//创建两个线程 生产者线程 消费者线程
//生产者线程
void* producer(void* arg)
{
	node_t* new = NULL; 
	while(1)
	{
		//加锁
		pthread_mutex_lock(&mutex);
		new = malloc(sizeof(node_t));
		if(NULL == new)
		{
			printf("malloc failed...\n");
			break;
		}
		memset(new,0,sizeof(node_t));
		//1-100
		new->data = random()%100 + 1;
		new->next = NULL;
		printf("生产者生产产品%d\n",new->data);
		//头插法
		new->next=head;
		head=new;
		//解锁
		pthread_mutex_unlock(&mutex);
		//唤醒因为条件变量而阻塞的线程
		pthread_cond_signal(&cond);
		sleep(random()%3+1);//随机睡眠
	}
	pthread_exit(NULL);
}
//消费者线程
void* customer(void* arg)
{
	node_t* tmp = NULL;
	//循环消费
	while(1)
	{
		pthread_mutex_lock(&mutex);
		if(NULL == head)
		{
			//printf("产品链表为空...先休息两秒钟...\n");
			//若链表为空 就阻塞
			pthread_cond_wait(&cond,&mutex);
		}
		else
		{
			tmp = head;
			head = head->next;
			printf("消费者消耗产品%d\n",tmp->data);
			free(tmp);
			//解锁
			pthread_mutex_unlock(&mutex);
			sleep(random()%3+1);
		}
	}
	pthread_exit(NULL);
}


int main()
{
	pthread_t = tid1=-1,tid2=-1;
	//设置随机种子
	srandom(getpid());
	//初始化条件变量
	ret = pthread_cond_init(&cond,NULL);
	if(0 != ret)
	{
		printf("pthread_cond_init failed...\n");
		return 1;
	}
	//初始化互斥量
	ret = pthread_mutex_init(&mutex,NULL);
	if(0 != ret)
	{
		printf("pthread_mutex_init failed...\n");
		return 1;
	}
	
	
	pthread_create(&tid1,NULL,producer,NULL);//创建生产者线程
	pthread_create(&tid2,NULL,customer,NULL);//创建消费者线程

	//等待两个线程结束,回收线程资源
	pthread_join(tid1,NULL);
	pthread_join(tid2,NULL);

	//销毁
	pthread_cond_destroy(&cond);
	pthread)_mutex_destroy(&mutex);
	return 0;
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值