动态高优先权优先调度算法 实验代码
时间: 2023-10-23 11:13:08 浏览: 102
以下是一个动态高优先权优先调度算法的实验代码,仅供参考:
```
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 100
typedef struct {
int pid; // 进程ID
int priority; // 进程优先级
int burst; // 进程执行时间
int wait; // 进程等待时间
int turnaround; // 进程周转时间
int arrival; // 进程到达时间
} Process;
// 按进程到达时间排序
void sort(Process *p, int n) {
int i, j;
for(i = 0; i < n-1; i++) {
for(j = i+1; j < n; j++) {
if(p[i].arrival > p[j].arrival) {
Process temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
}
int main() {
int n, i, j, time = 0, sum_burst = 0, sum_wait = 0, sum_turnaround = 0;
Process p[MAX];
bool completed[MAX] = {false};
printf("Enter the number of processes: ");
scanf("%d", &n);
for(i = 0; i < n; i++) {
printf("Enter the arrival time, burst time and priority of process %d: ", i+1);
scanf("%d %d %d", &p[i].arrival, &p[i].burst, &p[i].priority);
p[i].pid = i+1;
sum_burst += p[i].burst;
}
sort(p, n);
printf("\nProcess\tArrival\tBurst\tPriority\tWait\tTurnaround\n");
// 动态高优先权优先调度算法
while(time < sum_burst) {
int highest_priority = -1, index;
for(i = 0; i < n; i++) {
if(p[i].arrival <= time && !completed[i]) {
if(p[i].priority > highest_priority) {
highest_priority = p[i].priority;
index = i;
}
}
}
p[index].wait = time - p[index].arrival;
p[index].turnaround = p[index].wait + p[index].burst;
sum_wait += p[index].wait;
sum_turnaround += p[index].turnaround;
completed[index] = true;
time += p[index].burst;
printf("P%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d\n", p[index].pid, p[index].arrival, p[index].burst, p[index].priority, p[index].wait, p[index].turnaround);
}
printf("\nAverage waiting time: %f", (float)sum_wait/n);
printf("\nAverage turnaround time: %f", (float)sum_turnaround/n);
return 0;
}
```
该代码使用C语言实现了动态高优先权优先调度算法。用户输入进程的到达时间、执行时间和优先级后,程序按照到达时间进行排序,然后采用动态高优先权优先调度算法进行调度,计算每个进程的等待时间和周转时间,并输出结果。最后,计算平均等待时间和平均周转时间,并输出结果。
阅读全文