多级反馈队列调度算法c语言
时间: 2023-05-22 12:03:18 浏览: 261
C语言实现多级反馈队列调度算法
实现的关键在于循环遍历多个队列,同时需要实现时间片轮转的功能。下面是一个简单的多级反馈队列调度算法的C语言实现示例:
```
#include <stdio.h>
struct process {
int id;
int arrival_time;
int burst_time;
int priority;
int waiting_time;
int turnaround_time;
int remaining_time;
};
int quantum[] = {1, 2, 4};
int n_queues = 3;
int n_processes;
struct process process_list[100];
void schedule() {
int t = 0;
int completed = 0;
int queue[100];
int head[n_queues], tail[n_queues];
for (int i = 0; i < n_queues; i++) {
head[i] = -1;
tail[i] = -1;
}
for (int i = 0; i < n_processes; i++) {
if (process_list[i].arrival_time == 0) {
queue[++tail[0]] = i;
}
}
while (completed < n_processes) {
int current = -1;
for (int i = 0; i < n_queues; i++) {
if (head[i] <= tail[i]) {
current = queue[head[i]];
break;
}
}
if (current < 0) {
printf("Error: No valid process found at time %d.\n", t);
break;
}
int q = 0;
while (q < n_queues && process_list[current].remaining_time <= quantum[q]) {
q++;
}
int remaining = process_list[current].remaining_time - quantum[q-1];
t += quantum[q-1];
process_list[current].remaining_time = remaining;
process_list[current].priority = q;
if (remaining > 0) {
queue[++tail[q]] = current;
head[q] = (head[q] < 0) ? tail[q] : head[q];
} else {
completed++;
int wait_time = t - process_list[current].arrival_time - process_list[current].burst_time;
int turn_time = t - process_list[current].arrival_time;
process_list[current].waiting_time = wait_time;
process_list[current].turnaround_time = turn_time;
head[q]++;
}
}
}
int main() {
printf("Enter the number of processes:\n");
scanf("%d", &n_processes);
printf("Enter arrival time, burst time and priority for each process:\n");
for (int i = 0; i < n_processes; i++) {
scanf("%d%d%d", &process_list[i].arrival_time, &process_list[i].burst_time, &process_list[i].priority);
process_list[i].id = i+1;
process_list[i].remaining_time = process_list[i].burst_time;
}
schedule();
printf("Process\tArrival\tBurst\tPriority\tWait\tTurnaround\n");
for (int i = 0; i < n_processes; i++) {
printf("%d\t%d\t%d\t%d\t%d\t%d\n", process_list[i].id, process_list[i].arrival_time, process_list[i].burst_time, process_list[i].priority, process_list[i].waiting_time, process_list[i].turnaround_time);
}
return 0;
}
```
请问你还有什么问题?
阅读全文