0
点赞
收藏
分享

微信扫一扫

用c语言实现“生产者和消费者”问题

霍华德 2022-04-18 阅读 48

实验要求:要求程序运行时,按任意键停止,显示各种信息

#include <stdio.h>
#include<stdlib.h>
#include<time.h>
int mutex=1;
int empty=10;
int full=0;
int buf[10];
int front=0,rear=0;
int i;
//p操作 .申请 
void p(int *x)
{
	*x=(*x)-1;	
}
//v操作 .释放 
void v(int *x)
{
	*x=(*x)+1;	
}

void produce_thing(int *x)
{
	*x='p';
	
 } 
void enter_thing(int x)
{
	buf[front]=x;
	printf("输入一个%c到buf[%d]中\n",buf[front],front);
	front=(front+1)%10;
 } 
void nazou_thing(int *y)
{
	printf("从buf[%d]中取走%c,", rear,buf[rear]);
	*y=buf[rear];
	buf[rear]='q';
	rear=(rear+1)%10; 
}

void xiaohao_thing(int y)
{
	printf("消耗buf取出的产品%c\n",y);
	}	

void producer(void);
void consumer(void);


void producer(void)
{
	int a;
	while(1)
	{
		Sleep(1000);
		produce_thing(&a);
	    p(&empty);
		p(&mutex);
		enter_thing(a);
		if(kbhit())
{
			printf("生产者生产了%d个产品\n",front);
		//	printf("消费者消费了%d个产品",rear);
		    printf("生产者进行,消费者等待\n"); 
			system("pause");
}
		v(&mutex);
		v(&full);
		
		if(full!=10)
        {
		if(suijishu(i)==1)
        	producer();
        else
			consumer();	
	    }
	    else
			consumer();
		//if(full==10)
		// consumer();
	}
}
void consumer(void)
{
	int b;
	while(1)
	{
		Sleep(1000);
		p(&full);
		p(&mutex);
		nazou_thing(&b);
		
		v(&mutex); 
		v(&empty);
		xiaohao_thing(b);
		if(kbhit())
{
		//	printf("生产者生产了%d个产品",front);
			printf("消费者消费了%d个产品\n",rear);
			printf("消费者进行,生产者等待\n");
			system("pause");
}       
		if(empty!=10)
        {
		if(suijishu(i)==0)
        	consumer();
        else
			producer();	
	    }
	    else
			producer();
	}
}

suijishu(int i)//建立随机数,对是进行消费还是生产进行判断 
{
	srand((unsigned)time(NULL));
	i=rand()%2;
	return i;
}

int main(void)
{
	producer();
    return 0;

	//system("pause");
}

1.程序中consumer和producer是随机进行,机会均等,运用rand()函数进行随机数的创建,来选择是生产者进行还是消费者进行。

2.程序使用kbhit()和system("pause");进行任意键停止程序

存在问题:当按下任意键后只能显示上一步操作后的结果,如上一步操作的是生产者,那么任意键停止后只能显示生产者的信息

举报

相关推荐

0 条评论