高优先权调度算法的c语言代码实现
时间: 2023-06-17 15:02:06 浏览: 168
高优先权调度算法(High Priority Scheduling Algorithm)是一种优先级调度算法,它的特点是优先调度高优先级的进程,以保证高优先级进程的优先执行。下面是该算法的C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_PROCESS 10
struct process {
int pid;
int burst_time;
int priority;
};
void swap(struct process *x, struct process *y) {
struct process temp = *x;
*x = *y;
*y = temp;
}
void sort_by_priority(struct process *processes, int n) {
int i, j;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (processes[j].priority < processes[j+1].priority) {
swap(&processes[j], &processes[j+1]);
}
}
}
}
int main() {
int n, i, total_time = 0;
float avg_wait_time = 0.0, avg_turnaround_time = 0.0;
struct process processes[MAX_PROCESS];
printf("Enter the number of processes: ");
scanf("%d", &n);
for (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;
total_time += processes[i].burst_time;
}
sort_by_priority(processes, n);
printf("\nProcess\tBurst Time\tPriority\tWaiting Time\tTurnaround Time\n");
int current_time = 0;
for (i = 0; i < n; i++) {
printf("%d\t%d\t\t%d\t\t", processes[i].pid, processes[i].burst_time, processes[i].priority);
int waiting_time = current_time;
current_time += processes[i].burst_time;
int turnaround_time = current_time;
printf("%d\t\t%d\n", waiting_time, turnaround_time);
avg_wait_time += waiting_time;
avg_turnaround_time += turnaround_time;
}
avg_wait_time /= n;
avg_turnaround_time /= n;
printf("\nAverage waiting time: %.2f", avg_wait_time);
printf("\nAverage turnaround time: %.2f\n", avg_turnaround_time);
return 0;
}
```
该代码实现中,我们首先定义了一个 `struct process` 结构体,用来表示一个进程的信息,包括进程ID、执行时间和优先级。然后定义了一个 `swap` 函数,用来交换两个进程的信息。接着实现了一个 `sort_by_priority` 函数,用来按照优先级对进程进行排序。最后,在 `main` 函数中,我们首先读入所有进程的信息,并计算总的执行时间。然后对进程按照优先级进行排序,并输出每个进程的信息,包括等待时间和周转时间。最后计算出平均等待时间和平均周转时间,并输出结果。
需要注意的是,该实现中没有考虑抢占式调度,即如果一个高优先级的进程在执行过程中有一个更高优先级的进程到达,那么它会立即被抢占。如果需要考虑抢占式调度,需要对代码进行修改。
阅读全文