C++队列模拟作业任务调度(FCFS 先来先服务调度算法)

一、背景介绍

什么是FCFS(先来先服务):

如果早就绪的进程排在就绪队列的前面,迟就绪的进程排在就绪队列的后面,那么先来先服务(FCFS: first come first service)总是把当前处于就绪队列之首的那个进程调度到运行状态。也就说,它只考虑进程进入就绪队列的先后,而不考虑它的下一个CPU周期的长短及其他因素。FCFS算法简单易行,是一种非抢占式策略,但性能却不大好。

基本思想:

先来先服务的调度算法:最简单的调度算法,既可以用于作业调度 ,也可以用于程序调度,当作业调度中采用该算法时,系统将按照作业到达的先后次序来进行调度,优先从后备队列中,选择一个或多个位于队列头部的作业,把他们调入内存,分配所需资源、创建进程,然后放入“就绪队列”,直到该进程运行到完成或发生某事件堵塞后,进程调度程序才将处理机分配给其他进程。
所以FCFS的核心点就是:我们要根据作业的到达时间以及运行时间来对作业进行安排,这样就能做到让先到达的任务被系统先服务。

二、 代码

#include<iostream>
#include<queue>
#include<algorithm>
#include<windows.h>
#include<time.h>
#include <thread>
using namespace std;
#define MAX_SIZE 10
int n,max_time;
std::thread threads[MAX_SIZE];
struct Job {
    
    
    int id;
    int run_time;
    int arrive_time;
    int level;
    string print_work;
};
int cmp(const Job& s1, const Job& s2) {
    
    //自己定义的排序规则 
    if (s1.arrive_time == s2.arrive_time)
        return s1.run_time < s2.run_time;
    return s1.arrive_time < s2.arrive_time;
}
queue<Job> work,q,p;
Job job[MAX_SIZE];
Job temp;
void CreateJob() {
    
    
    for (int i = 0; i < MAX_SIZE; i++) {
    
    
        job[i].id = -1;
    }
    for (int i = 0; i < n; i++) {
    
    
        job[i].id = i+1;
        cout << "请输入运行时间、到达时间、打印内容:";
        cin >> job[i].run_time >> job[i].arrive_time >> job[i].print_work;
    }
    sort(job, job + n, cmp);
    for (int i = 0; i < n; i++) {
    
    
        job[i].level = i + 1;
        q.push(job[i]);
    }
}

void FCFServed() {
    
    
    auto t = clock();
    work = q;
    double starttime = 0;
    double finishtime = 0;
    cout << "Starting the FCFS..." << endl;
    cout << "JobId  " << "arrive_time  " << "run_time  " << "start_time  " << "finish_time  " << "print_work  "<<"level"<< endl;
    while (!work.empty()) {
    
    
            Sleep(1000* work.front().run_time);//op
            starttime = work.front().arrive_time;
            finishtime = starttime + work.front().run_time;
            cout << "  " << work.front().id << "          " << work.front().arrive_time << "             " << work.front().run_time << "        " << starttime << "          " << finishtime << "          " << work.front().print_work << "          " << work.front().level << endl;
            work.pop();
    }
    cout << "经过的时间为:"<< (clock() - t)/1000<<"s"<< endl;
}
int main()
{
    
    
    cout << "请输入作业个数:";
    cin >> n;
    CreateJob();
    FCFServed();
    cout << endl;
    system("pause");
}

三、效果图:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43663263/article/details/105902969