操作系统优先级调度算法C语言实现
时间: 2023-08-01 20:14:13 浏览: 126
以下是优先级调度算法的 C 语言源代码实现:
```
#include<stdio.h>
//进程控制块
struct process {
int pid; //进程 ID
int arrival_time; //到达时间
int burst_time; //执行时间
int priority; //优先级
};
int main() {
int n, i, j, total_wait_time = 0, total_turnaround_time = 0;
struct process p[10], temp;
float avg_wait_time, avg_turnaround_time;
//输入进程数
printf("Enter the number of processes: ");
scanf("%d", &n);
//输入每个进程的到达时间、执行时间和优先级
for(i = 0; i < n; i++) {
printf("Enter arrival time, burst time and priority for process %d: ", i + 1);
scanf("%d %d %d", &p[i].arrival_time, &p[i].burst_time, &p[i].priority);
p[i].pid = i + 1;
}
//按照优先级对进程进行排序
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;
}
}
}
//计算等待时间和周转时间
total_wait_time = 0;
for(i = 0; i < n; i++) {
total_wait_time += total_turnaround_time - p[i].arrival_time;
total_turnaround_time += p[i].burst_time;
}
//计算平均等待时间和平均周转时间
avg_wait_time = (float)total_wait_time / n;
avg_turnaround_time = (float)total_turnaround_time / n;
//输出结果
printf("\nProcess\tArrival Time\tBurst Time\tPriority\tWait Time\tTurnaround Time\n");
for(i = 0; i < n; i++) {
printf("%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d\n", p[i].pid, p[i].arrival_time, p[i].burst_time, p[i].priority, total_turnaround_time - p[i].arrival_time - p[i].burst_time, total_turnaround_time - p[i].arrival_time);
}
printf("\nAverage Wait Time: %.2f\n", avg_wait_time);
printf("Average Turnaround Time: %.2f\n", avg_turnaround_time);
return 0;
}
```
注意:该代码仅为示例,可能存在错误或不完善之处,仅供参考。
阅读全文