用c语言写进程调度算法
时间: 2023-10-11 08:13:25 浏览: 82
下面是一个简单的进程调度算法,使用C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_PROCESSES 10
typedef struct {
int pid; // 进程ID
int burst_time; // 进程的CPU时间
int priority; // 进程的优先级
int waiting_time; // 进程的等待时间
int turnaround_time; // 进程的周转时间
} Process;
int main() {
int num_processes;
int i, j, min_priority, min_priority_index;
float avg_waiting_time = 0.0, avg_turnaround_time = 0.0;
Process processes[MAX_PROCESSES];
printf("Enter the number of processes: ");
scanf("%d", &num_processes);
// 获取进程信息
for (i = 0; i < num_processes; i++) {
printf("Enter the burst time and priority of process %d: ", i + 1);
scanf("%d %d", &processes[i].burst_time, &processes[i].priority);
processes[i].pid = i + 1;
}
// 进程按照优先级排序
for (i = 0; i < num_processes; i++) {
min_priority = processes[i].priority;
min_priority_index = i;
for (j = i + 1; j < num_processes; j++) {
if (processes[j].priority < min_priority) {
min_priority = processes[j].priority;
min_priority_index = j;
}
}
// 交换进程位置
Process temp = processes[i];
processes[i] = processes[min_priority_index];
processes[min_priority_index] = temp;
}
// 计算等待时间和周转时间
processes[0].waiting_time = 0;
for (i = 1; i < num_processes; i++) {
processes[i].waiting_time = processes[i - 1].waiting_time + processes[i - 1].burst_time;
processes[i].turnaround_time = processes[i].waiting_time + processes[i].burst_time;
}
// 计算平均等待时间和平均周转时间
for (i = 0; i < num_processes; i++) {
avg_waiting_time += processes[i].waiting_time;
avg_turnaround_time += processes[i].turnaround_time;
}
avg_waiting_time /= num_processes;
avg_turnaround_time /= num_processes;
// 打印进程信息和结果
printf("PID\tBurst Time\tPriority\tWaiting Time\tTurnaround Time\n");
for (i = 0; i < num_processes; i++) {
printf("%d\t%d\t\t%d\t\t%d\t\t%d\n", processes[i].pid, processes[i].burst_time, processes[i].priority, processes[i].waiting_time, processes[i].turnaround_time);
}
printf("Average waiting time: %f\n", avg_waiting_time);
printf("Average turnaround time: %f\n", avg_turnaround_time);
return 0;
}
```
这个程序实现了一个简单的进程调度算法,基于优先级对进程进行排序,并计算每个进程的等待时间和周转时间。
阅读全文