实验2:磁盘调度 2.1实验目的 1、对磁盘调度的相关知识作进一步的了解,明确磁盘调度的原理。 2、加深理解磁盘调度的主要任务。 3、通过编程,掌握磁盘调度的主要算法。 2.2实验内容 1、对于如下给定的一组磁盘访问进行调度: 请求服务到达 A B C D E F G H I J K L M N 访问的磁道号 30 50 100 180 20 90 150 70 80 10 160 120 40 110 2、要求分别采用先来先服务、最短寻道优先以及电梯调度算法进行调度。 3、要求给出每种算法中磁盘访问的顺序,计算出平均移动道数。 4、假定当前读写头在90号,电梯调度算法向磁道号增加的方向移动。
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstdio>
#include<string.h>
using namespace std;
#define num 14
#define now 90
struct disk {
char id;
int pos;
}node[num];
void init() {
char a[num] = { 'A','B','C','D','E','F','G','H','I','G','K','L','M','N' };
int b[num] = { 30,50,100,180,20,90,150,70,80,10,160,120,40,110 };
for (int i = 0; i < num; i++) {
node[i].id = a[i];
node[i].pos = b[i];
}
}
void show(int sum, char* ans) {
cout << "磁盘访问顺序为:";
for (int i = 0; i < num; i++)
cout << ans[i] << " ";
cout << "\n平均移动道数为:" << double(sum) / num<< endl;
}
void FCFS() {
cout << "----------先来先服务算法----------\n";
int cur = now;
char ans[num];
int sum=0;
for (int i = 0; i < num; i++) {
ans[i] = node[i].id;
sum += abs(node[i].pos - cur);
cur = node[i].pos;
}
show(sum, ans);
}
void SSTF() {
cout << "----------最短寻道时间算法----------\n";
int cur = now;
char ans[num];
int sum = 0;
bool flag[num];
memset(flag, false, num);
for (int j = 0; j < num; j++) {
int stop = -1, min = 10000;
for (int i = 0; i < num; i++) {
if (flag[i] == true) continue;
if (min > abs(node[i].pos - cur)) {
min = abs(node[i].pos - cur);
stop = i;
}
}
flag[stop] = true;
sum += min;
ans[j] = node[stop].id;
cur = node[stop].pos;
}
show(sum, ans);
}
bool cmp(disk A, disk B) {
return A.pos < B.pos;
}
void SCAN() {
cout << "----------电梯调度算法----------\n";
int cur = now;
int sum = 0,cnt=0;
char ans[num];
disk cnode[num];
for (int i = 0; i < num; i++)
cnode[i] = node[i];
sort(cnode, cnode + num, cmp);
int stop = num;
for (int i = 0; i < num; i++) {
if (cnode[i].pos >= cur) {
stop = i;
break;
}
}
for (int i = stop; i < num; i++) {
sum += abs(cnode[i].pos - cur);
cur = cnode[i].pos;
ans[cnt++] = cnode[i].id;
}
for (int i = stop - 1; i >= 0; i--) {
sum += abs(cnode[i].pos - cur);
cur = cnode[i].pos;
ans[cnt++] = cnode[i].id;
}
show(sum, ans);
}
int main() {
while (true) {
init();
cout << "请选择磁盘调度算法:" << endl;
cout << "1.FCFS 2.SSTF 3.SCAN 4.结束进程" << endl;
int choice;
cin >> choice;
cout << endl;
switch (choice)
{
case 1: FCFS(); break;
case 2: SSTF(); break;
case 3: SCAN(); break;
case 4: exit(1);break;
}
}
return 0;
}
运行结果
|