给出优先级调度的C语言算法
时间: 2023-12-01 17:55:25 浏览: 101
好的,以下是一个优先级调度的 C 语言算法:
```c
#include <stdio.h>
struct process {
int pid;
int burst_time;
int priority;
int waiting_time;
int turnaround_time;
};
void sort_by_priority(struct process *p, int n) {
int i, j;
struct process temp;
for(i = 0; i < n-1; i++) {
for(j = i+1; j < n; j++) {
if(p[i].priority > p[j].priority) {
temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
}
void find_waiting_time(struct process *p, int n) {
int i;
p[0].waiting_time = 0;
for(i = 1; i < n; i++) {
p[i].waiting_time = p[i-1].waiting_time + p[i-1].burst_time;
}
}
void find_turnaround_time(struct process *p, int n) {
int i;
for(i = 0; i < n; i++) {
p[i].turnaround_time = p[i].waiting_time + p[i].burst_time;
}
}
void find_avg_time(struct process *p, int n) {
int i, total_waiting_time = 0, total_turnaround_time = 0;
for(i = 0; i < n; i++) {
total_waiting_time += p[i].waiting_time;
total_turnaround_time += p[i].turnaround_time;
}
float avg_waiting_time = (float)total_waiting_time / (float)n;
float avg_turnaround_time = (float)total_turnaround_time / (float)n;
printf("Average Waiting Time: %f\n", avg_waiting_time);
printf("Average Turnaround Time: %f\n", avg_turnaround_time);
}
void display(struct process *p, int n) {
int i;
printf("PID\tBurst Time\tPriority\tWaiting Time\tTurnaround Time\n");
for(i = 0; i < n; i++) {
printf("%d\t%d\t\t%d\t\t%d\t\t%d\n", p[i].pid, p[i].burst_time, p[i].priority, p[i].waiting_time, p[i].turnaround_time);
}
}
int main() {
int n, i;
printf("Enter number of processes: ");
scanf("%d", &n);
struct process p[n];
for(i = 0; i < n; i++) {
p[i].pid = i+1;
printf("Enter burst time and priority of process %d: ", i+1);
scanf("%d %d", &p[i].burst_time, &p[i].priority);
}
sort_by_priority(p, n);
find_waiting_time(p, n);
find_turnaround_time(p, n);
find_avg_time(p, n);
display(p, n);
return 0;
}
```
这个算法通过将进程按照优先级从小到大排序,然后计算每个进程的等待时间和周转时间,最终输出每个进程以及平均等待时间和平均周转时间。
阅读全文