📄 进程调度.cpp
字号:
#include "stdio.h"
#include "malloc.h"
#include "string.h"
#include "time.h"
#include <stdlib.h>
#define NULL 0
struct process{
char name[20];
struct process *next;
int time;
int priority;
char state;
};
struct process *creatlist(struct process *l)
{
struct process *p,*q;
char s1[]="P1",s2[]="P2",s3[]="P3",s4[]="P4",s5[]="P5";
int i;
l=(struct process*)malloc(sizeof(struct process));
p=l;
for(i=0;i<5;i++)
{
q=(struct process*)malloc(sizeof(struct process));
p->next=q;
p=q;
if(i==4)
p->next=NULL;
}
p=l;
strcpy(p->next->name,s2);
p->next->time=4;
p->next->state='R';
p->next->priority=5;//5
p=p->next;
strcpy(p->next->name,s4);
p->next->time=2;
p->next->state='R';
p->next->priority=4;//4
p=p->next;
strcpy(p->next->name,s3);
p->next->time=1;
p->next->state='R';
p->next->priority=3;//3
p=p->next;
strcpy(p->next->name,s5);
p->next->time=4;
p->next->state='R';
p->next->priority=2;//2
p=p->next;
strcpy(p->next->name,s1);
p->next->time=5;
p->next->state='R';
p->next->priority=1;//1
return l;
}
void run(struct process *l)
{
struct process *p,*q,*o;
char control;
int t=time(0),i,m,n=1;
p=l->next;
while(1)
{
if(time(0)==t+1)//每秒执行一次
{
/*手动控制逐步测试for(i=0;;i++)
{
scanf("%c",&control);
if(control=='\n')
break;
}*/
system("cls"); //刷屏
t=time(0);
printf("\n\n\n\n正在运行的程序:\n");
printf("%s %d %d %c\n\n",p->name,p->time,p->priority,p->state);//打印正在运行的程序
p->time--;
p->priority--;
if(p->priority<0)
p->priority=0;
q=p->next;//打印正在等待的程序
printf("正在等待的程序:\n");
while(q!=NULL)
{
printf("%s %d %d %c\n",q->name,q->time,q->priority,q->state);
q=q->next;
}
printf("\n\n\n系统时间片:\n");
for(m=0;m<n;m++)
{
if(m%4==0)
printf("\n");
printf("_______ ");
}
if(p->time==0)//如果所需时间为0则将PCB移到队列尾.
{
p->state='E';
q=o=p->next;
while(o!=NULL)
{
q=o;
o=q->next;
}
l->next=p->next;
q->next=p;
p->next=NULL;
}
else//否则调整PCB队列.
{
q=p;
o=p->next;
while(p->priority<=o->priority&&o!=NULL&&o->state!='E')
{
q=o;
o=q->next;
}
if(o!=p->next)
{
l->next=p->next;
if(o!=NULL)//插到队中
{
p->next=o;
q->next=p;
}
else//插到队尾
{
q->next=p;
p->next=NULL;
}
}
}
p=l->next;
if(l->next->time==0)//所有程序所需运行时间为0,结束.
{
system("cls");
printf("\n\n\n\n正在运行的程序:\n\n\n");
q=p;
printf("正在等待的程序:\n");
while(q!=NULL)
{
printf("%s %d %d %c\n",q->name,q->time,q->priority,q->state);
q=q->next;
}
printf("\n\n系统时间片:\n");
for(m=0;m<n;m++)
{
if(m%4==0)
printf("\n");
printf("_______ ");
}
break;
}
n++;
}
}
printf("\n\n所有程序运行结束.\n\n");
}
void main()
{
struct process *l=NULL;
l=creatlist(l);
run(l);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -