优先级调度算法c语言代码
时间: 2023-07-25 11:03:29 浏览: 108
c优先调度算法代码
以下是一个基于优先级调度算法的简单 C 语言代码示例:
```
#include <stdio.h>
struct process {
int pid;
int priority;
int burst_time;
};
void sort_processes(struct process procs[], int n) {
int i, j;
struct process temp;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (procs[i].priority < procs[j].priority) {
temp = procs[i];
procs[i] = procs[j];
procs[j] = temp;
}
}
}
}
int main() {
int n, i;
float avg_wt = 0, avg_tat = 0;
struct process procs[20];
printf("Enter the number of processes: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("Enter details for process %d:\n", i + 1);
printf("Process ID: ");
scanf("%d", &procs[i].pid);
printf("Priority: ");
scanf("%d", &procs[i].priority);
printf("Burst time: ");
scanf("%d", &procs[i].burst_time);
}
sort_processes(procs, n);
int wt = 0, tat = 0;
printf("\nPID\tPriority\tBurst time\tWaiting time\tTurnaround time\n");
for (i = 0; i < n; i++) {
wt += procs[i].burst_time;
tat += wt - procs[i].burst_time;
printf("%d\t%d\t\t%d\t\t%d\t\t%d\n", procs[i].pid, procs[i].priority,
procs[i].burst_time, wt - procs[i].burst_time, wt);
}
avg_wt = (float)wt / n;
avg_tat = (float)tat / n;
printf("\nAverage waiting time: %0.2f", avg_wt);
printf("\nAverage turnaround time: %0.2f", avg_tat);
return 0;
}
```
该代码实现了一个简单的优先级调度算法,它使用结构体来存储进程的 ID、优先级和运行时间。在输入完所有进程的数据后,它将根据优先级对它们进行排序,并对它们进行调度以计算平均等待时间和平均周转时间。
阅读全文