时间:2020-11-27
一.算法描述
该算法为“最高优先数优先”调度算法,并采用了动态优先数为进程赋予随时间片进行而变化的优先级。PCB包含的信息有:进程名,状态,优先级,执行所需时间,已运行时间,指向下一PCB的指针(PCB以链表方式存储)。在进程未开始时为进程对应的PCB确定进程名、初始优先级、执行所需时间。并默认所以进程的状态为w(就绪)。
当进程开始轮转时,以时间片为轮转单位,选取就绪队列中优先级最高的进程(若优先级相同则按FCFS选取),将其状态设置为r(运行)。每一时间片只运行一个进程,运行结束后,该进程的已运行时间加1,若此时已运行时间等于所需时间,该进程执行完成,将其状态设置为f(完成),不再进入就绪队列;若小于所需时间,优先级减1(相当于就绪队列中的其余进程优先级加1),将其状态设置为w(就绪),然后按优先级插入就绪队列中。然后进入下一时间片,重复上述步骤,直至所有进程完成。
二.数据结构设计
该算法中涉及PCB的设计,PCB结构体中具有进程名、进程状态、优先级、执行所需时间、已经运行时间、指向下一PCB的指针(PCB以链表方式存储)。PCB之间以链表的方式存储。
代码中含有函数sort(按优先级降序排序),createPCB(创建PCB),space(求就绪队列长度),check(显示运行状态),destoryPCB(进程完成后,释放PCB),running(运行进程)。
部分代码:
#include "stdio.h"
#include <stdlib.h>
#include <conio.h>
#define NULL 0
//定义PCB
struct pcb{
char name[10];//进程名
char state;//进程状态
int super;//优先级
int needTime;//进程需要的总运行时间
int alreadyUseTime;//进程已运行的时间
struct pcb* link;//指针
}*ready=NULL,*p;
typedef struct pcb PCB;
//按优先数降序排序
void sort(){
PCB *p1, *p2;
int insert=0;
if((ready==NULL)||((p->super)>(ready->super))){//优先级最大者,插入队首
p->link=ready;
ready=p;
}else{//进程比较优先级,插入适当的位置中
p1=ready;
p2=p1->link;
while(p2!=NULL){
if((p->super)>(p2->super)){
p->link=p2;
p1->link=p;
p2=NULL;
insert=1;
}else{
p1=p2->link;
p2=p2->link;
}
}
if(insert==0)
p1->link=p;
}
}
//创建进程控制块PCB
int createPCB(){
int i,num;
printf(" 请输入进程数?");
scanf("%d",&num);
printf("\n");
for(i=0;i<num;i++){
printf(" 进程编号%d:\n",i);
p=(PCB*)malloc(sizeof(PCB));
printf(" 进程名:");
scanf("%s",p->name);
printf(" 进程优先数:");
scanf("%d",&p->super);
printf(" 执行进程所需时间:");
scanf("%d",&p->needTime);
printf("\n");
p->alreadyUseTime=0;
p->state='w';
p->link=NULL;
sort();
}
return num;
}
//显示指定进程的PCB信息
void disp(PCB * pr){
printf("\n 进程名\t状态\t优先级\t运行时间\t已运行时间\n");
printf("|%s\t",pr->name);
printf("|%c\t",pr->state);
printf("|%d\t",pr->super);
printf("|%d\t\t",pr->needTime);
printf("|%d\t",pr->alreadyUseTime);
printf("\n");
} //完整代码请看git