设计一个有 N个进程共享的进程调度程序。
进程调度算法:采用最高优先数优先的调度算法(即把处理机分配给优先数最高的进程)和先来先服务算法。每个进程有一个进程控制块( PCB)表示。进程控制块可以包含如下信息:进程名、优先数、到达时间、需要运行时间、已用CPU时间、进程状态等等。 进程的优先数及需要的运行时间可以事先人为地指定(也可以由随机数产生)。进程的到达时间为进程输入的时间。进程的运行时间以时间片为单位进行计算。每个进程的状态可以是就绪 W(Wait)、运行R(Run)、或完成F(Finish)三种状态之一。就绪进程获得 CPU后都只能运行一个时间片。用已占用CPU时间加1来表示。如果运行一个时间片后,进程的已占用 CPU时间已达到所需要的运行时间,则撤消该进程,如果运行一个时间片后进程的已占用CPU时间还未达所需要的运行时间,也就是进程还需要继续运行,此时应将进程的优先数减1(即降低一级),然后把它插入就绪队列等待CPU。每进行一次调度程序都打印一次运行进程、就绪队列、以及各个进程的 PCB,以便进行检查。
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define getpch(type) (type *)malloc(sizeof(type))
int t = 0;
struct pcb { /* 定义进程控制块PCB */
char name[10]; //进程名
char state; //W/R/F
int super; //优先数
int ntime; //总运行时间
int rtime; //已耗时
struct pcb* link;
} *ready = NULL, * p;
typedef struct pcb PCB;
void sort() { /* 建立对进程进行优先级排列函数*/
p->link = NULL;
if (ready == NULL)
ready = p;
else {
if (p->super > ready->super) {
p->link = ready;
ready = p;
}
else {
PCB* f = ready;
while (1) {
if (f->link == NULL) {
f->link = p;
return;
}
else if (p->super > f->link->super) {
PCB* s = f->link;
f->link = p;
p->link = s;
return;
}
f = f->link;
}
}
}
}
void input() { /* 建立进程控制块函数*/
srand((unsigned)time(NULL));
int n;
string c;
cout << "输入1随机优先级+运行时间(1-5),输入其他字符则自定义参数:";
cin >> c;
cout << "请输入进程数目:";
cin >> n;
for (int i = 0; i < n; i++) {
p = getpch(PCB);
if (c == "1") {
cout << "请输入进程名" << i + 1 << ":";
cin >> p->name;
p->ntime = rand() % 4 + 1;
p->super = rand() % 9 + 1;
}
else {
cout << "请分别输入进程名、进程优先数、运行时间:";
cin >> p->name >> p->super >> p->ntime;
}
p->state = 'W';
p->rtime = 0;
sort();
}
}
void disp(PCB* pr) { /*建立进程显示函数,用于显示当前进程*/
cout << "进程名:" << pr->name << " ";
cout << "进程状态:" << pr->state << " ";
cout << "进程优先数:" << pr->super << " ";
cout << "进程总运行时间:" << pr->ntime << " ";
cout << "进程已经耗时:" << pr->rtime << endl;
}
void check() { /* 建立进程查看函数 */
cout << "-------------------" << " 正在运行中的进程 " << "------------------------------" << endl;
disp(p);
cout << "-------------------" << " 就绪队列中的进程 " << "------------------------------" << endl;
PCB* pr = ready;
while (pr != NULL) {
disp(pr);
pr = pr->link;
}
}
void destroy() { /*建立进程撤消函数(进程运行结束,撤消进程)*/
cout << "进程" << p->name << "运行完成,耗时" << p->ntime << "个CPU时间片" << endl;
free(p);
p = NULL;
}
void running() { /* 建立进程就绪函数(进程运行时间到,置就绪状态*/
p = ready;
ready = ready->link;
t++;
cout << endl << "这是第" << t << "个CPU时间片" << endl;
p->state = 'R';
check();
p->rtime++;
if (p->ntime == p->rtime)
destroy();
else {
p->super -= 1;
p->state = 'W';
sort();
}
if (p == NULL && ready == NULL)
cout << "全部完成,共耗时" << t << "个CPU时间片" << endl;
}
int main() { /*主函数*/
input();
while (p != NULL || ready != NULL)
running();
return 0;
}
实验结果: