处理器优先级调度模拟算法


</pre><pre name="code" class="cpp">#include "stdio.h"
#include<stdlib.h>
#include<conio.h>
#define getpch(type)(type*)malloc(sizeof(type))
#define NULL 0

struct pcb
{
	char name[10];
	char state;  //状态   w为等待,r是准备状态
	int super;   // 优先级,数字越大优先级越小
	int ntime;   //所需时间
	struct pcb *link;   //指向下一个进程的指针
}*ready=NULL,*p;   //p是当前进程

typedef struct pcb PCB;
//进程显示函数,显示当前函数
void disp(PCB *pr)
{
	printf("\nqname\tstate\tsuper\tntime\n");
	printf("|%s\t",pr->name);
	printf("|%c\t",pr->state);
	printf("|%d\t",pr->super);
	printf("|%d\t",pr->ntime);
	printf("\n");
} 
//进程优先级排列函数
void sort()
{
	PCB *first,*second;
	int insert=0;    //插入标记
	if((ready==NULL)||((p->super)<=(ready->super)))   //p的优先级高
	{
		p->link=ready;      //ready插在p后面
		ready=p;  
	}else                                            //p的优先级小于ready
	{
		first=ready;
		second=first->link;
		while(second!=NULL)           //循环比较p和second的优先级,遇到比p低的,p插到它前面
		{
			if((p->super)<(second->super))     //p优先级比second高,插到second前
			{
				p->link=second;
				first->link=p;
				second=NULL;                 //为了跳出循环
				insert=1;
			}else                 //p优先级不高于second ,first和second向后移
			{
				first=first->link;      
				second=second->link; 
			}
		}
		if(insert==0)    //循环后还没插入过(insert=0时),证明p优先级最低,插到队尾
		{
			first->link=p;   //此时first是队尾
			p->link=NULL;
		}
	}
}

//进程控制块函数
void input()
{
	int i;int num=5;    //5个进程
	for(i=0;i<num;i++)
	{
		printf("\n进程号No.%d",i+1);
		p=getpch(PCB);
		printf("\n输入进程名:");
		scanf("%s",p->name);
		printf("输入优先级数:");
		scanf("%d",&p->super);
		printf("输入运行时间:");
		scanf("%d",&p->ntime);
		printf("\n");
		p->state='w';
		p->link=NULL;
		sort();
	}
}



//进程撤销函数
void destroy()
{
	p->state='e';
	printf("\n进程[%s]已完成,\n",p->name);	
	free(p);

}

//进程就绪函数
void running()
{
	p->ntime--;
	p->super++;


}




//进程查看函数
void check()
{
	PCB *pr,*e;
	printf("\n***********当前正运行的进程是:%s",p->name);
	disp(p);
	pr=ready;
	printf("\n***********当前就绪的队列为:\n");
	while(pr!=NULL)
	{
		pr->state='w';
		disp(pr);
		pr=pr->link;
	}
	running();
	if(p->ntime==0)
	{
		destroy();
		
	}else{
		sort();
	}
}

void main()
{
	int h=0;
	char ch;
	input();

	while(ready!=NULL)
	{
		p=ready;
		ready=p->link;
		ch=getchar();
		h++;  //运行次数
		printf("\nThe excute number:%d\n",h);
		p->state='r';
		check();
		printf("\n按任意键继续。。。。。");
		ch=getchar();
	}
	printf("\n\n进程已经完成。\n");
	ch=getchar();
}



说实话,真不知道操作系统这课上的是神马,这个实验作业(优先级进程调度算法)真没想法,网上找不到实验要求一模一样的,狠了狠心,去了图书馆找,找来的根本有些问题也不是那么符合实验要求。。。。然后又狠了狠心,改了成了我想要的,其实还可以有些改进些地方,比如可以加个结束进程的队列什么的,,原谅我是个又笨又懒惰的人。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值