【操作系统原理】 多级队列调度算法(轮转算法和短进程优先算法)

题目很简单,直接上代码:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
typedef struct PCB {
	string name;
	int need;    //运行需要的时间
	int turn;    //周转时间
	PCB* next;    //PCB结构体指针
	PCB(string nam,int ned,int tur,PCB*nex) {     //构造函数
		name = nam;
		need = ned;
		turn = tur;
		next = nex;
	}
};

string name1[5] = { "p1","p2","p3","p4","p5" };
string name2[5] = { "p6","p7","p8","p9","p10" };
int time1[5] = { 16, 11,14,13,15 };
int time2[5] = { 21,18,10,7,14 };
int wait1[5] = {6,5,4,3,2};
int wait2[5] = { 1,2,3,4,5 };

//由于RQ1和RQ2采用两种不同的进程调度手段,所以每一个都单独创建一个结构体链表
PCB* RQ1, * RQ2, * finish=NULL;
PCB* one, * two;   //中间临时结点
int clock = 0;   //时钟初始化
int timepice = 7;   //时间片固定为7s

int circle(PCB* temp) {     //轮盘调度算法
	//轮盘调度算法:从链表头部开始遍历,首先计算每个进程需要的时间,如果可以在一个时间片timepice里完成
	//则完成后切换到下一个进程,如果不可以,则将其挪到链表尾,进行下一个进程
	PCB*start = temp;
	PCB*end = start;
	PCB* head = new PCB("a", 0, 0, temp);
	PCB*s = head;
	while (end->next) end = end->next;//用q来标记链表末尾位置
	while (start)
	{
		if (start->need > timepice)
		{
			clock += timepice;    //如果没有运行完该进程则将其挪至队尾
			start->need -= timepice;
			end->next = start;
			start = start->next;
			end = end->next;
			s->next = start;
			end->next = NULL;
		}
		else
		{
			clock += start->need;     //因为有表头指针的讯在 所以可以将始终标记最后一个need=0的结点
			start->need = 0;
			start->turn += clock;
			s = start;
			start = start->next;
		}
	}
	RQ1 = head->next;
	return clock;
}

int shortfirst(PCB* temp) {
	//短进程优先算法:该算法将需要运行的进程按需要运行的时间从小到大排序,先运行所需时间小的,运行完成之后再运行下一个
	//排序,每一次找到一个最小值,反复遍历五遍链表
	int min;   //保存最小值
	PCB* p=temp;   //保存头节点
	for (int i = 0; i < 5; i++) {
		min = p->need;
		while (temp != NULL) {     //遍历列表找最小值
			if (min > temp->need) {
				min = temp->need;
				temp = temp->next;
			}
			else { temp = temp->next; }
		}
		temp = p;   //归还头节点
		while (temp->need != min) {
			temp = temp->next;
		}
		clock += temp->need;
		temp->turn += clock;
		temp->need = 99999;   //将上一个最小结点的值置为无穷大  以免后续再次寻找最小值时找同一个结
		temp = p;
	}
	temp = p;   //归还头节点
	return clock;
}


int main() {
	RQ1 =new PCB(name1[0],time1[0],wait1[0],NULL);  //创建一个结点
	PCB* p = RQ1;
	for (int i = 1; i < 5; i++) {
		one = new PCB(name1[i], time1[i], wait1[i], NULL);
		p->next = one;
		p = p->next;     //将RQ1挪到中间结点后继承这个结点
	}
	RQ2 = new PCB(name2[0], time2[0], wait2[0], NULL);  //创建一个结点
	PCB* q = RQ2;
	for (int i = 1; i < 5; i++) {
		two = new PCB(name2[i], time2[i], wait2[i],NULL);
		q->next = two;
		q = q->next;
	}

	clock = circle(RQ1);   //RQ1采用轮转算法
	cout << "RQ1队列采用轮转算法,其中每个进程等待的时间为:" << endl;
	for (int i = 0; i < 5; i++) {
		cout << "P" << i << ": " << RQ1->turn << endl;
		RQ1 = RQ1->next;
	}

	clock = shortfirst(RQ2);   //RQ2采用短进程优先算法
	cout << "RQ2队列采用段进程优先算法,其中每个进程等待的时间为:" << endl;
	for (int i = 6; i < 11; i++) {
		cout << "P"<<i<<": "<<RQ2->turn << endl;
		RQ2 = RQ2->next;
	}
	return 0;
}

因为最后我只输出了turn的时间,如果那个need的时间也需要输出自己稍微加一行代码就可以啦!

上一篇:Transformer 论文:Attention Is All You Need


下一篇:Attention is all you need论文翻译