实现c++时间片轮转算法
时间: 2024-01-26 15:05:10 浏览: 25
时间片轮转算法是一种常见的 CPU 调度算法,可以实现多任务并发执行。下面是一个简单的 C++ 实现:
```c++
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
struct Process {
int pid; // 进程 ID
int burst_time; // 运行时间
int remaining_time; // 剩余时间
};
void time_slice_round_robin(vector<Process>& processes, int time_slice) {
queue<Process> ready_queue; // 就绪队列
int n = processes.size();
int total_burst_time = 0; // 所有进程的总运行时间
int current_time = 0; // 当前时间
int i = 0; // 当前执行的进程索引
// 计算总运行时间
for (int i = 0; i < n; i++) {
total_burst_time += processes[i].burst_time;
}
while (total_burst_time > 0) {
// 将到达当前时间的进程加入就绪队列
while (i < n && processes[i].burst_time <= current_time) {
ready_queue.push(processes[i]);
i++;
}
if (ready_queue.empty()) {
// 如果就绪队列为空,则将当前时间跳到下一个进程的到达时间
current_time = processes[i].burst_time;
} else {
// 从就绪队列中取出一个进程执行
Process current_process = ready_queue.front();
ready_queue.pop();
// 执行时间片
int execute_time = min(time_slice, current_process.remaining_time);
current_process.remaining_time -= execute_time;
// 更新总运行时间、当前时间和进程信息
total_burst_time -= execute_time;
current_time += execute_time;
if (current_process.remaining_time > 0) {
// 如果进程还有剩余时间,则将其加入就绪队列
ready_queue.push(current_process);
} else {
// 如果进程已经完成,则输出其信息
cout << "Process " << current_process.pid << " completed at time " << current_time << endl;
}
}
}
}
int main() {
vector<Process> processes = {
{1, 10, 10},
{2, 5, 5},
{3, 8, 8},
{4, 4, 4},
{5, 2, 2},
};
int time_slice = 3;
time_slice_round_robin(processes, time_slice);
return 0;
}
```
上面的程序定义了一个 `Process` 结构体,包含进程的 ID、运行时间和剩余时间。`time_slice_round_robin` 函数实现了时间片轮转算法,接受一个进程列表和时间片大小作为输入。程序先计算出所有进程的总运行时间,然后在一个循环中模拟 CPU 的执行过程。在每个时间片内,程序从就绪队列中取出一个进程执行,如果进程还有剩余时间,则将其加入就绪队列,否则输出进程完成的信息。在实际应用时,可以根据需要修改进程列表和时间片大小。