C++优先级调度算法实现与解析
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
// 进程控制块
struct ProcessControlBlock {
int process_id;
int service_time;
int remaining_time;
int priority;
};
// 自定义比较函数
struct ComparePriority {
bool operator()(const ProcessControlBlock& a, const ProcessControlBlock& b) {
return a.priority > b.priority;
}
};
// 优先级调度算法函数
void priorityScheduling(vector<ProcessControlBlock>& processes) {
priority_queue<ProcessControlBlock, vector<ProcessControlBlock>, ComparePriority> ready_queue;
int current_time = 0;
while (!processes.empty()) {
// 将所有进程添加到就绪队列
for (auto& process : processes) {
ready_queue.push(process);
}
ProcessControlBlock current_process = ready_queue.top();
ready_queue.pop();
current_time += current_process.remaining_time;
cout << 'Process ' << current_process.process_id << ' is scheduled and completed at time ' << current_time << endl;
// 降低其他进程的优先级
for (auto& process : processes) {
if (process.process_id != current_process.process_id) {
process.priority--;
}
}
// 移除已经完成的进程
processes.erase(remove_if(processes.begin(), processes.end(), [&](const ProcessControlBlock& process) {
return process.process_id == current_process.process_id;
}), processes.end());
// 清空就绪队列
while (!ready_queue.empty()) {
ready_queue.pop();
}
}
}
int main() {
vector<ProcessControlBlock> processes = {
{1, 10, 10, 3},
{2, 4, 4, 2},
{3, 6, 6, 1},
{4, 2, 2, 4}
};
priorityScheduling(processes);
return 0;
}
代码解析:
- 进程控制块 (ProcessControlBlock): 定义了一个结构体,包含进程ID、服务时间、剩余时间和优先级等属性。
- 自定义比较函数 (ComparePriority): 定义了一个结构体,重载了括号运算符,用于比较两个进程的优先级。
- 优先级调度算法函数 (priorityScheduling):
- 创建一个优先级队列
ready_queue,使用自定义比较函数ComparePriority比较进程优先级。 - 循环遍历进程列表,直到所有进程都被调度完成。
- 在每一次循环中,将所有进程添加到就绪队列中。
- 从就绪队列中获取优先级最高的进程
current_process。 - 模拟进程执行,更新当前时间
current_time。 - 降低其他进程的优先级。
- 从进程列表中移除已完成的进程。
- 清空就绪队列,为下一轮调度做准备。
- 创建一个优先级队列
- 主函数 (main): 创建一个进程列表,调用
priorityScheduling函数进行优先级调度,并输出调度结果。
运行结果:
Process 4 is scheduled and completed at time 2
Process 3 is scheduled and completed at time 8
Process 2 is scheduled and completed at time 12
Process 1 is scheduled and completed at time 22
这段代码演示了如何使用C++实现优先级调度算法,并通过一个简单的例子展示了算法的执行过程。你可以根据实际需求修改代码,例如调整优先级计算方式或添加其他进程属性等。
原文地址: https://www.cveoy.top/t/topic/EOO 著作权归作者所有。请勿转载和采集!