【课设】模拟优先数调度算法-非抢占式

来源:互联网 发布:用python写移动软件 编辑:程序博客网 时间:2024/05/13 10:48

优先数调度算法分为抢占式和非抢占式。

非抢占式:进程按优先数大小进行排列,优先数高的程序先运行。直到发生某种情况或运行完成才结束。

抢占式:进程按优先数大小进行排列,优先数高的程序先运行。每运行一次(优先数-1),即重新判断进程序列的优先数大小。只要有优先数更大的,便进行新的最大的优先数的进程

#include <stdio.h>#include <stdlib.h>#include <time.h>#include <iostream>using namespace std;struct PCB//定义PCB结构体 {int PN;//进程名称 struct PCB *next;//指向下一个进程 int run_time;//执行时间 int power;//优先数 bool state;//进程的状态 }; void time_random(int *t)//定义取时间随机数 { int i,number=0;srand((unsigned) time(NULL)); //用时间做种,每次产生随机数不一样,但还是可能会相同 for (i=0; i<5; i++)//取五个随机数,放入数组t中 {number = rand() % 21;//对21取余 while(number==0)//若余数为0,则一直取到不为0为止 number = rand() % 21; //产生1-20的随机数t[i]=number; //将随机数赋给数组 } } //初始化五个进程 void Init_PCB(int number,PCB *p){int power[10]={5,3,1,2,4,5,3,1,2,4};int t[5]={0};time_random(t);cout<<"开始初始化进程"<<endl;for(int i=0; i<5;i++){p[i].PN = i+1;p[i].run_time = t[i];    p[i].next=NULL;     p[i].state = 0;p[i].power=power[i+number];cout<<"- - - - - - - ->\n";}cout<<"初始化完成!"<<endl;}//打印 void Print(PCB *p){for(int i = 0;i<5;i++){cout<<"======================="<<endl;cout<<"进程名称: "<<p[i].PN<<endl;cout<<"下一个进程:"<<p[i].next<<endl;cout<<"运行时间: "<<p[i].run_time<<endl;cout<<"优先数:   " <<p[i].power<<endl;cout<<"状态:     "<<p[i].state<<endl; }}//根据优先数将其连起来 void Link(int number,PCB *q,PCB *p){switch(number){case 0:q->next=&p[0];p[0].next=&p[4];//5,3,1,2,4p[4].next=&p[1];p[1].next=&p[3];p[3].next=&p[2];p[2].next=NULL;break;case 1:q->next=&p[4];p[4].next=&p[3];//3,1,2,4,5p[3].next=&p[0];p[0].next=&p[2];p[2].next=&p[1];p[1].next=NULL;break;case 2:q->next=&p[3];p[3].next=&p[2];//1,2,4,5,3p[2].next=&p[4];p[4].next=&p[1];p[1].next=&p[0];p[0].next=NULL;break;case 3:q->next=&p[2];p[2].next=&p[1];//2,4,5,3,1p[1].next=&p[3];p[3].next=&p[0];p[0].next=&p[4];p[4].next=NULL;break;case 4:q->next=&p[1];p[1].next=&p[0];//4,5,3,1,2p[0].next=&p[2];p[2].next=&p[4];p[4].next=&p[3];p[3].next=NULL;break;}}void run(PCB *q) {printf("\n");for(q=q->next;q;q=q->next){printf("\np[%d]运行结束,运行时间%2d",q->PN,q->run_time--);}}void Print_End(PCB *p){while(p->next){printf("p%d->",p->PN);p=p->next;}}int main(){PCB p[5];PCB *q; PCB *c;int i = 0;int number = 0;srand((int)time(NULL));number = rand()%5;//初始化五个进程 Init_PCB(number,p);//根据number取余数来链到一起 Link(number,q,p);c=q; //把链好的Q赋值给c  //打印所有进程信息 Print(p);   //输出进程序列 printf("=======================\n");printf("进程序列:pi\n");for(q=q->next;q!=NULL;q=q->next){printf("p%d(%d)",q->PN /*,q->power,*/,q->run_time);if(q->next)printf("->");}//开始运行run(c);return 0;} 


2 0
原创粉丝点击