动态优先级轮转调度c语言代码
时间: 2023-10-12 21:05:15 浏览: 90
进程调度C#源代码优先级加轮转
4星 · 用户满意度95%
以下是一个简单的动态优先级轮转调度的 C 语言代码实现:
```c
#include <stdio.h>
#define MAX_PROCESS 10
#define TIME_QUANTUM 2
struct Process {
int pid;
int priority;
int burst_time;
int remaining_time;
};
int main() {
int n, time = 0, total_burst_time = 0, completed = 0;
struct Process processes[MAX_PROCESS];
printf("Enter the number of processes: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("Enter the burst time and priority for process %d: ", i + 1);
scanf("%d %d", &processes[i].burst_time, &processes[i].priority);
processes[i].pid = i + 1;
processes[i].remaining_time = processes[i].burst_time;
total_burst_time += processes[i].burst_time;
}
printf("\nGantt Chart:\n");
printf("0 ");
while (completed < n) {
int current_pid = -1, max_priority = -1;
for (int i = 0; i < n; i++) {
if (processes[i].remaining_time > 0 && processes[i].priority > max_priority && processes[i].burst_time > 0 && time >= processes[i].burst_time) {
current_pid = i;
max_priority = processes[i].priority;
}
}
if (current_pid == -1) {
printf("IDLE %d ", time);
time++;
continue;
}
printf("P%d %d ", processes[current_pid].pid, time);
int run_time = TIME_QUANTUM;
if (processes[current_pid].remaining_time < TIME_QUANTUM) {
run_time = processes[current_pid].remaining_time;
}
processes[current_pid].remaining_time -= run_time;
time += run_time;
if (processes[current_pid].remaining_time == 0) {
completed++;
}
}
printf("%d\n\n", time);
float waiting_time = 0, turnaround_time = 0;
for (int i = 0; i < n; i++) {
printf("Process %d:\n", processes[i].pid);
printf("Waiting Time: %d\n", time - processes[i].burst_time);
printf("Turnaround Time: %d\n\n", time);
waiting_time += time - processes[i].burst_time;
turnaround_time += time;
}
printf("Average Waiting Time: %.2f\n", waiting_time / n);
printf("Average Turnaround Time: %.2f\n", turnaround_time / n);
return 0;
}
```
在这个实现中,我们首先读取进程的数量以及每个进程的爆发时间和优先级。接下来,我们初始化每个进程的 PID,剩余时间和总爆发时间,并且计算出所有进程的总爆发时间。我们使用一个 while 循环来模拟调度算法的执行,直到所有进程都完成。
在每个循环迭代中,我们首先寻找具有最高优先级的进程,该进程仍然有剩余时间并且已经运行了至少一次。如果没有这样的进程,则我们打印出 IDLE 并增加时间片。否则,我们打印出该进程的 PID 并计算它在当前时间片内运行的时间。如果剩余时间小于时间片大小,则只运行剩余时间。
在进程完成后,我们增加 completed 变量的值,并计算等待时间和周转时间。最后,我们通过除以进程数来计算平均等待时间和平均周转时间,并将结果打印到控制台上。
阅读全文