非抢占式优先级调度算法c语言
时间: 2023-07-29 21:07:56 浏览: 65
下面是一个简单的非抢占式优先级调度算法的示例代码,使用C语言实现:
```c
#include <stdio.h>
#define MAX 5
struct process {
int pid;
int priority;
int burst_time;
int waiting_time;
int turnaround_time;
};
int main() {
struct process p[MAX], temp;
int i, j, n = 0;
float avg_waiting_time = 0, avg_turnaround_time = 0;
// 读入进程信息
printf("Enter the number of processes: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("Enter process %d details:\n", i+1);
printf("PID: ");
scanf("%d", &p[i].pid);
printf("Priority: ");
scanf("%d", &p[i].priority);
printf("Burst Time: ");
scanf("%d", &p[i].burst_time);
}
// 根据优先级排序
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;
}
}
}
// 计算等待时间和周转时间
p[0].waiting_time = 0;
p[0].turnaround_time = p[0].burst_time;
for (i = 1; i < n; i++) {
p[i].waiting_time = p[i-1].waiting_time + p[i-1].burst_time;
p[i].turnaround_time = p[i].waiting_time + p[i].burst_time;
}
// 计算平均等待时间和平均周转时间
for (i = 0; i < n; i++) {
avg_waiting_time += p[i].waiting_time;
avg_turnaround_time += p[i].turnaround_time;
}
avg_waiting_time /= n;
avg_turnaround_time /= n;
// 输出结果
printf("\nPID\tPriority\tBurst Time\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].priority, p[i].burst_time, p[i].waiting_time, p[i].turnaround_time);
}
printf("\nAverage Waiting Time: %.2f\n", avg_waiting_time);
printf("Average Turnaround Time: %.2f\n", avg_turnaround_time);
return 0;
}
```
该算法的基本思路是按照优先级对进程进行排序,然后依次执行优先级最高的进程。如果有多个进程具有相同的优先级,则按照先来先服务的原则依次执行。在执行每个进程时,需要计算它的等待时间和周转时间。最终,可以计算出所有进程的平均等待时间和平均周转时间。
阅读全文