任务目标: | 1.设计一个模拟单处理机调度算法; 2.巩固和加深对进程概念和进程调度算法的理解。 |
任务环境: | Windows 或Linux操作系统,C语言 |
编写程序完成单处理机系统中的进程调度,要求采用最高优先级优先调度算法,具体内容包括:
进程调度算法:采用最高优先级优先调度算法(即把处理机分配给优先级最高的进程)和先来先服务调度算法。每个进程用一个进程控制块(PCB)表示。进程控制块可以包含以下信息:进程名、优先数、到达时间、需要运行时间、已用CPU时间、进程状态等。进程优先数及需要的运行时间可以事先人为指定(也可由随机数产生)。进程的到达时间为进程的输入时间。进程的运行时间以时间片为单位进行计算。 图1 进程调度算法流程图 每个进程的状态可以是就绪W(Wait)、运行R(Run)或完成F(Finish)三种状态之一。就绪进程获得CPU后都只能运行一个时间片,用已占用CPU时间加1来表示。如果运行一个时间片后,进程的已占用CPU时间已达到所需要的运行时间,则撤销该进程,如果运行一个时间片后进程的已占用CPU时间还未达到所需要的运行时间,也就是进程还需要进行运行,此时应将进程的优先数减1(即降低一级),然后把它插入就绪队列等待CPU。 每进行一次,调度程序都打印一次运行进程、就绪队列以及各个进程的PCB,以便进行检查。重复以上过程,直到所有进程都完成为止。 进程调度算法流程图如图1所示。
#include<stdio.h> #include<stdlib.h> #include<conio.h> #define getpch(type)(type*)malloc(sizeof(type)) struct pcb{ char name[10]; char state; int super; int ntime; int rtime; struct pcb* link; }*ready=NULL,*p; typedef struct pcb PCB; sort() { PCB *first,*second; int insert=0; if((ready==NULL)||((p->super)>(ready->super))) { p->link=ready; ready=p; } else { first=ready; second=first->link; while(second!=NULL) { if((p->super)>(second->super)) { p->link=second; first->link=p; second=NULL; insert=1; } else { first=first->link; second=second->link; } } if(insert==0)first->link=p; } } input() { int i,num; system("cls"); printf("\n 请输入进程号?"); scanf("%d",&num); for(i=0;i<num;i++) { printf("\n 进程号No.%d:\n",i); p=getpch(PCB); printf("\n 输入进程名:"); scanf("%s",p->name); printf("\n 输入进程优先数:"); scanf("%d",&p->super); printf("\n 输入进程运行时间:"); scanf("%d",&p->ntime); printf("\n"); p->rtime=0; p->state='w'; p->link=NULL; sort(); } } int space() { int i=0;PCB* pr=ready; while(pr!=NULL) { i++; pr=pr->link; } return(1); } disp(PCB*pr) { printf("\n qname \t state \t super \t ndtime \t runtime \n"); printf("|%s\t",pr->name); printf("|%c\t",pr->state); printf("|%d\t",pr->super); printf("|%d\t",pr->ntime); printf("|%d\t",pr->rtime); printf("\n"); } check() { PCB* pr; printf("\n**** 当前正在运行的进程是:%s",p->name); disp(p); pr=ready; printf("\n**** 当前就绪队列状态为:\n"); while(pr!=NULL) { disp(pr); pr=pr->link; } } destroy() { printf("\n 进程 [%s] 已完成.\n",p->name); free(p); } running() { (p->rtime)++; if(p->rtime==p->ntime) destroy(); else { (p->super)--; p->state='w'; sort(); } } int main() { int len,h=0; char ch; input(); len=space(); while((len!=0)&&(ready!=NULL)) { ch=getchar(); h++; printf("\n The exrcute number:%d\n",h); p=ready; ready=p->link; p->state='R'; check(); running(); printf("\n 按任一键继续......"); ch=getchar(); } printf("\n\n 进程已经完成.\n"); ch=getchar(); return 0; }
|
04-06
01-27
8005
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
11-19
2503
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-07
2398
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)