线程下的生产者和消费者模型

本文讲的是多线程情况下生产者和消费者通过仓库(缓冲区)来传递数据的例子
在这里插入图片描述

#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#define MAX_VALUE 50
//栈结构
char house[MAX_VALUE] = {};
//栈的下标
int top = 0;
//互斥量,确保只有一个线程访问栈顶
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
//满仓条件变量(满仓时生产线睡眠)
pthread_cond_t full = PTHREAD_COND_INITIALIZER;
//空仓条件变量(空仓时消费者睡眠)
pthread_cond_t null = PTHREAD_COND_INITIALIZER;

//显示仓库
void show(char* who,char* op,char ch)
{
	printf("%s:",who);
	for(int i=0;i<=top;i++)
	{
		printf("%c",house[i]);
	}
	printf("%s%c\n",op,ch);
}

//生产线程
void* production(void* arg)
{
	char* who = (char*)arg;
	for(;;)
	{
		char ch = 'A' + rand() % 26;
		
		pthread_mutex_lock(&mutex);
		//检查是否满仓
		if(MAX_VALUE <= top)
		{
			printf("%s:满仓",who);
			pthread_cond_wait(&full,&mutex);
		}
		
		show(who,"<-",ch);
		//仓库入仓
		house[top++] = ch;	
		usleep(rand()%100000);
		//确认仓库不空,通知消费者
		pthread_cond_signal(&null);
		//解锁
		pthread_mutex_unlock(&mutex);
		usleep(rand()%100000);
	}
	return NULL;
}

void* consume(void* arg)
{
	char* who = (char*)arg;
	//仓库有货就会一直买
	for(;;)
	{
		//加锁
		pthread_mutex_lock(&mutex);
		//检查空仓
		if(0 == top)
		{
			printf("%s:空仓\n",who);
			pthread_cond_wait(&null,&mutex);
		}
		char ch = house[--top];
		show(who,"->",ch);
		
		usleep(rand()%100000);
		
		pthread_cond_signal(&full);
		pthread_mutex_unlock(&mutex);
		
		usleep(rand()%100000);
	}
}

int main()
{
	srand(time(NULL));
	pthread_t pid[10] = {};
	
	pthread_create(&pid[0],NULL,production,"生产1");
	pthread_create(&pid[1],NULL,consume,"消费1");
    pthread_create(&pid[2],NULL,production,"生产2");
    pthread_create(&pid[3],NULL,consume,"消费2");
    pthread_create(&pid[4],NULL,production,"生产3");
    pthread_create(&pid[5],NULL,consume,"消费3");
    pthread_create(&pid[6],NULL,production,"生产4");
    pthread_create(&pid[7],NULL,consume,"消费4");
    pthread_create(&pid[8],NULL,production,"生产5");
    pthread_create(&pid[9],NULL,consume,"消费5");
    
    for(int i=0;i<10;i++)
    {
    	pthread_join(pid[i],NULL);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值