⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 7.cpp

📁 CPU调度算法-优先级调度
💻 CPP
字号:
#include<stdio.h> 
#include<malloc.h> 
typedef struct Lnode 
{ 
char name[10]; 
struct Lnode *point; 
int priority; 
int runtime; 
char situation; 
}Lnode,*Linklist; //定义结点即定义pcb块 

void creatlist(Linklist &L,int n) //给每个结点初始化 
{ 
int i; 
Linklist p,l; 
L=(Linklist)malloc(sizeof(Lnode)); 
L->point=NULL; 
l=L; 
for(i=n;i>0;i--) 
{ 
p=(Linklist)malloc(sizeof(Lnode)); 
printf("Please input the name of the course\n"); 
getchar(); 
gets(p->name); 
printf("then input the priority and the runtime!\n"); 
scanf("%d %d",&p->priority,&p->runtime); 
p->situation='R'; 
p->point=NULL;L->point=p;l=p; //依次构造结点并非倒着构造 
} 
printf("\n"); 

} 

int Run(Linklist &L,Linklist p) //L为链头指针 
{ 
Linklist h=L->point; 
printf("Now the course %s is running!\n",p->name); //其实h即为head 

printf("Now The priority of the course is %d\n",p->priority); //只打印输出即可减操作已在 
//主函数执行!! 

printf("And The lefttime of this course is %d\n",--p->runtime); 
if(p->runtime==0) p->situation='C'; 

if(p->situation=='R') 
printf("This course's situation is R now!\n"); 
if(p->situation=='C') printf("This course's situation is C now!\n"); 

printf("The leftcourse of the queue are:"); 
while(h!=NULL) //situation为R即为在队列中就绪的 
{ //直接打印输出即可 
if(h->situation=='R') 
printf("%s ",h->name); 
h=h->point; 
} 
printf("\n"); 
printf("\n"); 
return 0; 
} 

//返回链表中优先级最大的!!! 
Linklist choose (Linklist L) 
{ 
Linklist p,m; 
int max=-10000; 
for(p=L->point;p!=NULL;p=p->point) 
{ 
if(max<p->priority) 
{ 
max=p->priority; 
m=p; 
} 
} 
return m; 
} 
//返回链表中runtime最大的值并且得是最后的一个!!! 
Linklist latest (Linklist L) 
{ 
Linklist p,m; 
int max=-1; 
for(p=L->point;p!=NULL;p=p->point) 
{ 
if(max<=p->runtime) 
{ 
max=p->runtime; 
m=p; 
} 
} 
return m; 
} 

void main() 
{ 
int n; //n是进程的个数 
Linklist L,m,nn,late; //L是表头,late指向runtime最长的,m为被选中的优先级最高的 
printf("pleast input the number of the course!\n"); 
scanf("%d",&n); 
creatlist(L,n); //创建一个头结点为L,个数为N的单向链表(按顺序链接) 
late=latest(L); //找到所需时间最长的 
nn=late; //给nn赋初值,没有报错! 
while(late->situation!='C') //循环条件 
{ 
m=choose(L); //选出优先级最高的 
if(m->priority==nn->priority&&nn->runtime!=0) //若m经一次处理后优先级仍是最高 
m=nn; //则继续执行他!! 
//if(m->priority>0) //优先级可以为负的!!考虑当优先级都为0的情况 
m->priority--; //priority放在Run函数外执行!! 
if(m->runtime>0) 
Run(L,m); //俩参数,头结点,和m. 
nn=m; 
late=latest(L); 
} 
} 


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -