时间片轮转调度算法的代码
时间: 2024-04-14 13:10:10 浏览: 11
下面是一个简单的时间片轮转调度算法的代码实现:
```c++
#include <iostream>
#include <queue>
using namespace std;
// 进程的数据结构
struct Process {
int pid; // 进程ID
int burstTime; // 运行时间
int remainingTime; // 剩余时间
};
// 时间片轮转调度算法
void roundRobinScheduling(Process processes[], int n, int quantum) {
queue<Process> readyQueue; // 就绪队列
int currentTime = 0; // 当前时间
// 初始化剩余时间
for (int i = 0; i < n; i++) {
processes[i].remainingTime = processes[i].burstTime;
}
// 循环调度进程
while (true) {
bool done = true; // 判断所有进程是否都完成了
for (int i = 0; i < n; i++) {
if (processes[i].remainingTime > 0) {
done = false; // 存在未完成的进程
if (processes[i].remainingTime > quantum) {
// 执行时间片
currentTime += quantum;
processes[i].remainingTime -= quantum;
readyQueue.push(processes[i]); // 加入就绪队列
} else {
// 执行完剩余时间
currentTime += processes[i].remainingTime;
processes[i].remainingTime = 0;
cout << "进程 " << processes[i].pid << " 在时间 " << currentTime << " 完成" << endl;
}
}
}
if (done) break; // 所有进程都完成了
// 执行就绪队列中的进程
while (!readyQueue.empty()) {
Process p = readyQueue.front();
readyQueue.pop();
if (p.remainingTime > 0) {
if (p.remainingTime > quantum) {
// 执行时间片
currentTime += quantum;
p.remainingTime -= quantum;
readyQueue.push(p); // 加入就绪队列
} else {
// 执行完剩余时间
currentTime += p.remainingTime;
p.remainingTime = 0;
cout << "进程 " << p.pid << " 在时间 " << currentTime << " 完成" << endl;
}
}
}
}
}
int main() {
Process processes[] = {{1, 10}, {2, 5}, {3, 8}};
int n = sizeof(processes) / sizeof(Process);
int quantum = 2;
roundRobinScheduling(processes, n, quantum);
return 0;
}
```
上面的代码中,定义了一个结构体 `Process` 表示进程,包括进程ID、运行时间和剩余时间。`roundRobinScheduling` 函数是时间片轮转调度算法的实现,接受进程数组、进程数量和时间片长度作为参数。首先初始化每个进程的剩余时间,然后循环调度进程,如果进程还有剩余时间,就执行一次时间片,将进程加入就绪队列;否则,输出进程完成信息。然后执行就绪队列中的进程,直到所有进程都完成。在 `main` 函数中定义了三个进程和时间片长度,调用 `roundRobinScheduling` 函数进行调度。