磁盘调度算法

#include<iostream>
#include<algorithm>
#include<ctime>
#include<cstdlib>

using namespace std;
class Core{
public:
    int* IOtable;//IO表
    int Nums;
    int CiDaoHao;//当前磁道号
    int Direct;//当前磁臂方向 1表示磁道增加 0表示磁道递减
    int PID;//当前进程
    int ToCiDao;//要访问的磁道号
    Core(int Nums){
        this->Nums=Nums;
        this->IOtable =new int[Nums];
        srand(time(NULL));
        for(int i=0;i<this->Nums;i++){
            IOtable[i] = rand()%200;
        }
        this->Direct = 1;
        cout<<" 当前磁道方向初始化为增加方向"<<endl;
        this->PID = 0;
        cout<<" 当前进程为0"<<endl;
        this->CiDaoHao = 100;
        cout<<" 当前磁道号为 100"<<endl;

    }
    ~Core(){
        cout<<" 磁盘调度结束";
    }
    void print(){
        cout<<" IO表如下所示:"<<endl;
        cout<<" 进程名\t"<<"| 要求访问的磁道"<<endl;
        for(int i=0;i<this->Nums;i++){
            cout<<" "<<i<<"\t"<<" |"<<this->IOtable[i]<<endl;
        }
    }
    void SCAN(){
        cout<<" 执行磁盘调度SCAN算法"<<endl;
        sort(this->IOtable,this->IOtable+this->Nums);
        cout<<" 当前磁道号为 "<<this->CiDaoHao<<endl;
        cout<<" 被访问的下一个磁道号 | 移动距离(磁道数)"<<endl;
        int sign = 0;
        int reCiDaoHao = this->CiDaoHao;
        int temp = 0;
        do{
            if(this->Direct==1){
                for(int i=0;i<this->Nums;i++){
                    if(this->IOtable[i]>=reCiDaoHao){
                        cout<<IOtable[i]<<"\t |"<<IOtable[i]-this->CiDaoHao<<endl;
                        temp+=(IOtable[i]-this->CiDaoHao);
                        this->CiDaoHao=IOtable[i];
                        sign++;
                    }
                }
                this->Direct=0;
            }
            if(this->Direct==0){
                for(int i=this->Nums-1;i>=0;i--){
                    if(this->IOtable[i]<reCiDaoHao){
                        cout<<IOtable[i]<<"\t |"<<this->CiDaoHao-IOtable[i]<<endl;
                        temp+=(this->CiDaoHao-IOtable[i]);
                        this->CiDaoHao=IOtable[i];
                        sign++;
                    }
                }
                this->Direct=1;
            }
        }while(sign<this->Nums);
        temp/=this->Nums;
        cout<<" 平均寻道长度="<<temp<<endl;
    }
    void Request(){
        cout<<" 接受请求"<<endl;
        srand(time(NULL));
        for(int i=0;i<this->Nums;i++){
            this->IOtable[i] = rand()%200;
        }
        print();
    }
};

int main(){
    Core* core = new Core(8);
    core->print();
    srand(time(NULL));
    char check;
    do{
        if(rand()%10>5) core->SCAN();
        else core->Request();
        cout<<" 是否继续? 继续按0 退出按1"<<endl;
        cin>>check;
    }while(check!=1);
    delete core;
}

运行结果如下所示:

 

posted @ 2019-05-30 00:16  秃桔子  阅读(416)  评论(0编辑  收藏  举报

如果您有编程方面或者学术方面的需求请在微信公众号搜索

桔子科研


或者识别下方二维码,第一时间获取编程有趣的知识和最新科研学术成果。