操作系统实验之磁盘调度算法模拟(最短寻道时间优先SSTF 和 扫描算法SCAN)
- 最短寻道时间优先SSTF
- 要求每次访问的磁道与当前磁头所在的磁道距离最近、
- 也就是每次访问距离磁头最近的磁道
- 扫描算法SCAN
- 由里向外地访问,直到再无更外的磁道需要访问时,才将磁臂转向为自外向里移动
- 磁盘调度算法 详细介绍
模拟代码:
#include<stdio.h>
#include<algorithm>
#include<math.h>
using namespace std;
const int MAX_DISK = 200;
int Disk[MAX_DISK + 1];
int DISK_NUMBER = 0;
int DIRECTION = 1;
int CURRENT_DISK;
int compare(int a,int b){
return a > b;
}
void SSTF(){
int left,right,now;
double length = 0,avg_length = 0;
if(DIRECTION == 1)
sort(Disk,Disk + DISK_NUMBER + 1);
else
sort(Disk,Disk + DISK_NUMBER + 1,compare);
for(int i = 0; i <= DISK_NUMBER; i++)
{
if(Disk[i] == CURRENT_DISK)
{
now = i;
left = i -1;
right = i + 1;
}
}
while(!(left == -1 && right == DISK_NUMBER + 1))
{
if(left <= -1)
{
length += fabs(Disk[right] - Disk[now]);
for(int i = right; i <= DISK_NUMBER; i++)
{
if(i > right)
length += fabs(Disk[i] - Disk[i - 1]);
printf("%d ",Disk[i]);
}
break;
}
if(right == DISK_NUMBER + 1)
{
length += fabs(Disk[now] - Disk[left]);
for(int i = left; i >=0; i--)
{
if(i < left)
length += fabs(Disk[i] - Disk[i + 1]);
printf("%d ",Disk[i]);
}
break;
}
if(fabs(Disk[right] - Disk[now]) <= fabs(Disk[now] - Disk[left]))
{
length += fabs(Disk[right] - Disk[now]);
printf("%d ",Disk[right]);
now = right;
right++;
}
else if(fabs(Disk[right] - Disk[now]) > fabs(Disk[now] - Disk[left]))
{
length += fabs(Disk[now] - Disk[left]);
printf("%d ",Disk[left]);
now = left;
left--;
}
}
avg_length = length / DISK_NUMBER;
printf("平均寻道时间为:%lf",avg_length);
}
void SCAN()
{
int left,right,now;
double length = 0,avg_length = 0;
if(DIRECTION == 1)
sort(Disk,Disk + DISK_NUMBER + 1);
else
sort(Disk,Disk + DISK_NUMBER + 1,compare);
for(int i = 0; i <= DISK_NUMBER; i++)
{
if(Disk[i] == CURRENT_DISK)
{
now = i;
left = i -1;
right = i + 1;
}
}
length += fabs(Disk[now] - Disk[right]);
for(int i = right; i <= DISK_NUMBER; i++)
{
if(i > right)
length += fabs(Disk[i] - Disk[i -1]);
printf("%d ",Disk[i]);
}
length += fabs(Disk[DISK_NUMBER] - Disk[left]);
for(int i = left; i>=0; i--)
{
if(i < left)
length += fabs(Disk[i] - Disk[i + 1]);
printf("%d ",Disk[i]);
}
avg_length = length / DISK_NUMBER;
printf("平均寻道时间为:%lf",avg_length);
}
int main()
{
printf("input the number of the disk\n");
scanf("%d",&DISK_NUMBER);
printf("input the Disk[]\n");
for(int i = 0; i < DISK_NUMBER; i++)
scanf("%d",&Disk[i]);
printf("input the direction of the disk , right = 1 and left = 0\n");
scanf("%d",&DIRECTION);
printf("input the current disk\n");
scanf("%d",&CURRENT_DISK);
Disk[DISK_NUMBER] = CURRENT_DISK;
printf("the answer of the SSTF is:\n");
SSTF();
printf("\nthe answer of the SCAN is:\n");
SCAN();
return 0;
}