操作系统实验1:进程调度程序---基于时间片轮转的最高优先数优先算法

418 阅读1分钟

1. 调度原理

2. 要求

3. 程序流程图

4. 实现思路

优先队列(priority_queue)实现:用优先队列模拟就绪队列,以PCB的优先级作为队列的优先级,每次迭代从优先队列中取出优先级最大的进程(队头出队),执行一个时间片(runtime++),判断该进程是否已经完成(ndtime==runtime),若还没完成,按照算法将其优先级减1(super--),再将其塞回优先队列(push);若已经完成,则将该进程移出就绪队列(pop)。

5. C++代码

#include<iostream>
#include<queue>
#include<vector>
using namespace std;
class PCB{
private:
    string name;
    string state;
    int super;
    int ndtime;
    int runtime;
public:
    PCB(string name,int super,int ndtime){
        this->name = name;
        this->super = super;
        this->ndtime = ndtime;
        runtime=0;
        state="W";
    }
    
    bool operator<(const PCB& p)const{
        return super<p.super;
    }
    
    void minusSuper(){
        if(super>0)super--;
    }
    
    bool isFinish(){
        return ndtime==runtime;
    }
    
    void plusRuntime(){
        if(!isFinish())
            runtime++;
    }
    
    void printInfo(){
        cout<<"p_name"<<"\t"<<"state"<<"\t"<<"super"<<"\t"<<"ndtime"<<"\t"<<"runtime"<<"\n";
        cout<<name<<"\t"<<state<<"\t"<<super<<"\t"<<ndtime<<"\t"<<runtime<<"\n";
    }
    
    void stateChangesTo(string newState){
    	this->state = newState;
	}
	
	string getName(){
		return name;
	}
	
};

int main(void){
    priority_queue<PCB> queue;
    string name;
    int super;
    int ndtime;
    int process_count;
    
    cout<<"请输入进程的个数?";  cin>>process_count; cout<<endl;
    for(int i=0;i<process_count;i++){
        cout<<"进程号No."<<i<<":"<<endl;
        cout<<"输入进程名:"; cin>>name;
        cout<<"输入进程优先数(0~99):"; cin>>super;
        cout<<"输入进程运行时间:"; cin>>ndtime;
        cout<<endl;
        PCB pcb(name,super,ndtime);
        queue.push(pcb);
    }
    
    system("pause");
    
    int times=0;
    while(!queue.empty()){
        times++;
        PCB cur = queue.top();
        cur.stateChangesTo("R");
        queue.pop();
        cout<<"*--*--*--*--*--*--*--*--*--* Times:"<<times<<" *--*--*--*--*--*--*--*--*--*"<<endl;
        cout<<"*--*--*--*--*--*--*--* 当前正在运行的进程是:"<<cur.getName()<<" *--*--*--*--*--*--*"<<endl;
        cur.printInfo();
        cout<<"*--*--*--*--*--*--*--* 当前就绪队列状态为: *--*--*--*--*--*--*--*--*"<<endl;
        //遍历优先队列中所有元素
        vector<PCB> tempv;
        while(!queue.empty()){
            tempv.push_back(queue.top());
            queue.pop();
        }
        for(int i=0;i<tempv.size();i++){
            tempv[i].printInfo();
            queue.push(tempv[i]);
        }
        cur.plusRuntime();
        cur.minusSuper();
        if(cur.isFinish()){
            cout<<"时间片到期,进程["<<cur.getName()<<"]已经完成"<<endl;
            cur.stateChangesTo("F"); 
        }else{
            cur.stateChangesTo("W");
            queue.push(cur);cout<<endl;
        }
        system("pause");
        cout<<endl;
    }
    
    cout<<"所有进程都结束"<<endl;
}

6.实现效果