操作系统 短进程优先算法(C++)

思路

用结构体数组存储pcb表,用优先队列维护就绪的进程,优先队列存储pair<pcb的序号, 进程运行所需时间>,按照运行时间从小到大排序。然后运行即可。

例子

在这里插入图片描述

代码

#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <string.h>
#include <cstdio>
#include <cstdlib>
#include <queue>
using namespace std;

#define MP(a,b) make_pair(a, b)
typedef pair<int, int> P;///pcb中的序号 服务时间

const int maxn_program = 1e5 + 10;
const int maxn_name = 1e2 + 10;

int N;              ///进程数目
int now_time;       ///现在的时间

struct node{
    char program_name[maxn_name];       ///进程名
    int arrive_time;                    ///到达时间
    int run_time;                       ///服务时间
    int finished_time;                  ///完成时间
    int wait_time;                      ///周转时间
    double with_value_wait_time;        ///带权周转时间
    char status = 'W';     ///进程状态(W,R,F)
}program[maxn_program];

bool cmp(node a, node b){
    if(a.arrive_time == b.arrive_time)
        return a.run_time < b.run_time;
    return a.arrive_time < b.arrive_time;
}

struct cmp2{
    template<typename T, typename U>
    bool operator()(T const& left, U const &right) {
        if (left.second > right.second)
            return true;
        return false;
    }
};

priority_queue <P, vector<P>, cmp2> que;

void out_put(){
    printf("now_time:%d\n", now_time);
    printf("%10s %10s %10s %10s %10s %10s %10s\n", "进程名", "到达时间", "服务时间", "完成时间", "周转时间", "带权周转时间", "进程状态");
    for(int i = 1; i <= N; i++){
        printf("%10s %10d %10d %10d %10d %10.2f %10c\n", program[i].program_name, program[i].arrive_time, program[i].run_time, program[i].finished_time, program[i].wait_time, program[i].with_value_wait_time, program[i].status);
    }
}

void run_it(){
    int pos = que.top().first;
    now_time += que.top().second;
    program[pos].finished_time = now_time;
    program[pos].status = 'F';
    program[pos].wait_time = now_time - program[pos].arrive_time;
    program[pos].with_value_wait_time = (double)program[pos].wait_time / program[pos].run_time;
    que.pop();
}

int main(){
    printf("输入进程数目:");
    scanf("%d", &N);
    printf("依次输入各进程的进程名、到达时间、服务时间:");
    for(int i = 1; i <= N; i++){
        scanf("%s %d %d", &program[i].program_name, &program[i].arrive_time, &program[i].run_time);
    }
    ///按到达时间排序,同时到达按照运行时间从短到长排序
    sort(program + 1, program + 1 + N, cmp);
    ///out_put();      ///输出pcb
    for(int pos = 1; pos <= N;){
        while(pos <= N && program[pos].arrive_time <= now_time){
            que.push(MP(pos, program[pos].run_time));///压入就绪队列
            pos++;
        }
        if(!que.empty())///如果que不为空
            run_it();///执行一个进程
        out_put();
    }
    while(!que.empty()){
        run_it();
        out_put();///输出pcb
    }
    return 0;
}
/*
5
A 0 4
B 1 3
C 2 5
D 3 2
E 4 4
*/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章