c语言实现最高优先数优先算法的进程调度实验的代码
时间: 2023-12-21 07:06:48 浏览: 88
实验三 最高优先级调度代码 .rar_pcb_优先级调度_先来先服务_进程 优先 调度
下面是一个简单的 C 语言程序,实现了最高优先数优先算法的进程调度实验。
```c
#include <stdio.h>
#define MAX_PROCESSES 10
// 定义进程结构体
typedef struct process {
int id; // 进程 ID
int arrival_time; // 进程到达时间
int burst_time; // 进程执行时间
int priority; // 进程优先级
int waiting_time; // 进程等待时间
int turnaround_time; // 进程周转时间
} Process;
int main() {
int i, j, total_waiting_time = 0, total_turnaround_time = 0;
float avg_waiting_time, avg_turnaround_time;
Process processes[MAX_PROCESSES], temp;
int num_processes;
// 输入进程数
printf("Enter the number of processes: ");
scanf("%d", &num_processes);
// 输入每个进程的信息
for (i = 0; i < num_processes; i++) {
printf("Enter the arrival time, burst time and priority of process %d: ", i + 1);
scanf("%d %d %d", &processes[i].arrival_time, &processes[i].burst_time, &processes[i].priority);
processes[i].id = i + 1;
}
// 对进程按照优先级进行排序
for (i = 0; i < num_processes - 1; i++) {
for (j = i + 1; j < num_processes; j++) {
if (processes[i].priority < processes[j].priority) {
temp = processes[i];
processes[i] = processes[j];
processes[j] = temp;
}
}
}
// 计算每个进程的等待时间和周转时间
for (i = 0; i < num_processes; i++) {
if (i == 0) {
processes[i].waiting_time = 0;
processes[i].turnaround_time = processes[i].burst_time;
} else {
processes[i].waiting_time = processes[i - 1].turnaround_time - processes[i].arrival_time;
if (processes[i].waiting_time < 0) {
processes[i].waiting_time = 0;
}
processes[i].turnaround_time = processes[i].waiting_time + processes[i].burst_time;
}
total_waiting_time += processes[i].waiting_time;
total_turnaround_time += processes[i].turnaround_time;
}
// 输出每个进程的等待时间和周转时间
printf("Process ID\tArrival Time\tBurst Time\tPriority\tWaiting Time\tTurnaround Time\n");
for (i = 0; i < num_processes; i++) {
printf("%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d\n", processes[i].id, processes[i].arrival_time,
processes[i].burst_time, processes[i].priority, processes[i].waiting_time,
processes[i].turnaround_time);
}
// 输出平均等待时间和平均周转时间
avg_waiting_time = (float) total_waiting_time / num_processes;
avg_turnaround_time = (float) total_turnaround_time / num_processes;
printf("Average waiting time: %f\n", avg_waiting_time);
printf("Average turnaround time: %f\n", avg_turnaround_time);
return 0;
}
```
该程序首先输入进程数和每个进程的到达时间、执行时间和优先级,然后按照优先级对进程进行排序,计算每个进程的等待时间和周转时间,并输出每个进程的信息和平均等待时间和平均周转时间。
阅读全文