用C语言编写并调试一个先来先服务和短作业优先调度算法进程等待程序
时间: 2023-11-16 13:06:49 浏览: 118
以下是使用C语言编写的先来先服务和短作业优先调度算法进程等待程序:
先来先服务(FCFS)调度算法:
```c
#include <stdio.h>
// FCFS调度算法
void fcfs(int n, int arrival_time[], int burst_time[]) {
int waiting_time[n], turnaround_time[n];
waiting_time[0] = 0;
int i;
for (i = 1; i < n; i++) {
waiting_time[i] = waiting_time[i - 1] + burst_time[i - 1];
}
for (i = 0; i < n; i++) {
turnaround_time[i] = waiting_time[i] + burst_time[i];
}
float avg_waiting_time = 0, avg_turnaround_time = 0;
for (i = 0; i < n; i++) {
avg_waiting_time += waiting_time[i];
avg_turnaround_time += turnaround_time[i];
}
avg_waiting_time /= n;
avg_turnaround_time /= n;
printf("FCFS调度算法\n");
printf("进程编号 到达时间 运行时间 等待时间 周转时间\n");
for (i = 0; i < n; i++) {
printf("%-10d %-10d %-10d %-10d %-10d\n", i + 1, arrival_time[i], burst_time[i], waiting_time[i], turnaround_time[i]);
}
printf("平均等待时间:%f\n", avg_waiting_time);
printf("平均周转时间:%f\n", avg_turnaround_time);
}
int main() {
int n;
printf("请输入进程数:");
scanf("%d", &n);
int arrival_time[n], burst_time[n];
int i;
for (i = 0; i < n; i++) {
printf("请输入第%d个进程的到达时间和运行时间:", i + 1);
scanf("%d%d", &arrival_time[i], &burst_time[i]);
}
fcfs(n, arrival_time, burst_time);
return 0;
}
```
短作业优先(SJF)调度算法:
```c
#include <stdio.h>
// SJF调度算法
void sjf(int n, int arrival_time[], int burst_time[]) {
int waiting_time[n], turnaround_time[n];
int i, j, completed = 0, run_time = 0;
for (i = 0; i < n; i++) {
waiting_time[i] = 0;
turnaround_time[i] = 0;
}
while (completed < n) {
int shortest_process = -1;
int shortest_burst_time = 1000000;
for (i = 0; i < n; i++) {
if (arrival_time[i] <= run_time && burst_time[i] < shortest_burst_time && turnaround_time[i] == 0) {
shortest_burst_time = burst_time[i];
shortest_process = i;
}
}
if (shortest_process == -1) {
run_time++;
continue;
}
waiting_time[shortest_process] = run_time - arrival_time[shortest_process];
turnaround_time[shortest_process] = waiting_time[shortest_process] + burst_time[shortest_process];
run_time += burst_time[shortest_process];
completed++;
}
float avg_waiting_time = 0, avg_turnaround_time = 0;
for (i = 0; i < n; i++) {
avg_waiting_time += waiting_time[i];
avg_turnaround_time += turnaround_time[i];
}
avg_waiting_time /= n;
avg_turnaround_time /= n;
printf("SJF调度算法\n");
printf("进程编号 到达时间 运行时间 等待时间 周转时间\n");
for (i = 0; i < n; i++) {
printf("%-10d %-10d %-10d %-10d %-10d\n", i + 1, arrival_time[i], burst_time[i], waiting_time[i], turnaround_time[i]);
}
printf("平均等待时间:%f\n", avg_waiting_time);
printf("平均周转时间:%f\n", avg_turnaround_time);
}
int main() {
int n;
printf("请输入进程数:");
scanf("%d", &n);
int arrival_time[n], burst_time[n];
int i;
for (i = 0; i < n; i++) {
printf("请输入第%d个进程的到达时间和运行时间:", i + 1);
scanf("%d%d", &arrival_time[i], &burst_time[i]);
}
sjf(n, arrival_time, burst_time);
return 0;
}
```
以上两个程序都是使用C语言编写的,可以通过编译器进行编译和调试。其中,`n`表示进程数,`arrival_time`和`burst_time`分别表示进程的到达时间和运行时间。两个程序的输出结果都包括每个进程的信息,以及平均等待时间和平均周转时间。
阅读全文