【实验名称】
进程调度——时间片轮转算法
【实验名称】
巩固和加深处理机调度的概念,设计按时间片轮转算法。
【实验原理】
利用按时间片轮转算法,设计调度算法,模拟实现处理机的调度。
【源代码】
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
typedef struct PCB {//用一个结构体来模拟进程PCB
int time = 0;
string name;
struct PCB* next = NULL;//声明一个结构体指针,指向其下一个结构体
}PCB, * PCBlist;
void Input(int n, PCBlist front) {//n是进程的数目,front是进程的头指针
PCBlist P = front;
for (n; n > 0; n--) {//用for语句,依次输入各个进程的信息
PCBlist M = new PCB;
cout << "输入进程名: ";
cin >> M->name;
cout << "输入进程需要运行时间: ";
cin >> M->time;
M->next = NULL;
P->next = M;
P = P->next;
}
P->next = front;//把最后一个进程的next,指向头front,构成循环
}
void Print(int nt, int nt1, PCBlist M) {//构造一个打印函数,打印进程执行的各个步骤
if (nt != nt1)
cout << nt << "------->" << nt1 << ": " << M->name << endl;
else return;
}
int main() {
int n, t;//n是进程数目,t是时间片
int nt = 0;//nt是目前时刻,方便打印进程的执行过程
cout << "请输入进程数和时间片:" << endl;
cin >> n >> t;//输入进程数n和时间片t
PCBlist P = new PCB;//P是辅助指针,用来指向正在执行的进程
P->name = "fan";
P->time = 0;
P->next = NULL;
PCBlist front = new PCB;
front->time = 0;
front->name = "进入下一轮:";
// front->next = NULL;
Input(n, front);//使用输入函数
P = front;
while (front->next != front) {//判断,存在没有执行完的进程
// if (Judge(t, P->next)) {
if (t <= P->next->time||P->next) {//判断,将要执行的进程的执行时间大于时间片
Print(nt, nt + t, P->next);
P->next->time -= t;
nt += t;
if (P->next->time != 0) {//更新辅助指针P
P = P->next;
}
else {//剔除已经执行结束的进程
PCBlist N = P->next;
P->next = P->next->next;
delete N;
}
}
else {//对于将要执行的进程的执行时间小于时间片的情况,另行处理
Print(nt, nt + P->next->time, P->next);
nt = nt + P->next->time;
PCBlist N = P->next;
P->next = P->next->next;
delete N;
}
}
return 0;
}
【结果截图】
【代码优点和缺陷】
首先这个代码比较简洁,重要步骤都有注释,有助于大家理解其思想。
写这个代码的时候,时间不太够。所以有些缺陷:时间片设置成1的时候,一切正常,但是设置成其他数字的时候,就会出问题。小伙伴们借鉴的时候,可以参考这个代码的思想,用设置断点的方式,改进一下代码结构,应该问题不大。大家也可以求出周转时间、服务时间,再用 周转时间/服务时间 来求出带权周转时间。