c++实现先进先出调度算法
时间: 2023-11-14 20:05:28 浏览: 101
先来先服务(First Come First Served,FCFS)调度算法是一种简单的进程调度算法,按照进程到达的先后顺序进行调度。当一个进程进入就绪队列后,它会被放在队列的末尾,等待CPU的调度。当CPU空闲时,会从队列的头部取出一个进程进行执行,直到该进程执行完毕或者发生阻塞,才会执行下一个进程。因此,FCFS算法的优点是简单易懂,缺点是平均等待时间较长,不适用于长作业。
以下是C++实现先进先出调度算法的示例代码:
```C++
#include <iostream>
#include <queue>
using namespace std;
struct Process {
int id; // 进程ID
int arriveTime; // 到达时间
int burstTime; // 执行时间
int finishTime; // 完成时间
int turnaroundTime; // 周转时间
double weightedTurnaroundTime; // 带权周转时间
};
bool operator<(const Process& p1, const Process& p2) {
return p1.arriveTime > p2.arriveTime; // 按到达时间从小到大排序
}
void FCFS(vector<Process>& processes) {
int n = processes.size();
queue<Process> readyQueue;
int currentTime = 0;
for (int i = 0; i < n; i++) {
while (!readyQueue.empty() && currentTime < processes[i].arriveTime) {
Process p = readyQueue.front();
readyQueue.pop();
p.finishTime = currentTime + p.burstTime;
p.turnaroundTime = p.finishTime - p.arriveTime;
p.weightedTurnaroundTime = (double)p.turnaroundTime / p.burstTime;
cout << "进程" << p.id << "执行完毕,完成时间为" << p.finishTime << ",周转时间为" << p.turnaroundTime << ",带权周转时间为" << p.weightedTurnaroundTime << endl;
currentTime = p.finishTime;
}
if (currentTime < processes[i].arriveTime) {
currentTime = processes[i].arriveTime;
}
readyQueue.push(processes[i]);
}
while (!readyQueue.empty()) {
Process p = readyQueue.front();
readyQueue.pop();
p.finishTime = currentTime + p.burstTime;
p.turnaroundTime = p.finishTime - p.arriveTime;
p.weightedTurnaroundTime = (double)p.turnaroundTime / p.burstTime;
cout << "进程" << p.id << "执行完毕,完成时间为" << p.finishTime << ",周转时间为" << p.turnaroundTime << ",带权周转时间为" << p.weightedTurnaroundTime << endl;
currentTime = p.finishTime;
}
}
int main() {
vector<Process> processes = {{1, 0, 5}, {2, 1, 3}, {3, 2, 8}, {4, 3, 6}, {5, 4, 4}};
FCFS(processes);
return 0;
}
```
阅读全文