非抢占式短进程优先调度算法c语言怎么写
时间: 2023-06-10 20:02:38 浏览: 157
非抢占式短进程优先调度算法的C语言实现如下:
```c
#include<stdio.h>
#include<stdlib.h>
struct Process {
int pid;
int burst_time;
int waiting_time;
int turn_around_time;
};
typedef struct Process process;
void swap(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void sort(process p[], int n) {
int i, j;
for (i = 0; i < n-1; i++)
for (j = i+1; j < n; j++)
if (p[i].burst_time > p[j].burst_time) {
swap(&p[i].burst_time, &p[j].burst_time);
swap(&p[i].pid, &p[j].pid);
}
}
void non_preemptive_sjf(process p[], int n) {
int i, j, total_waiting_time = 0, total_turn_around_time = 0;
int time = 0;
sort(p, n);
printf("PID\tBurst Time\tWaiting Time\tTurnaround Time\n");
for (i = 0; i < n; i++) {
while (p[i].burst_time == 0) // skip processes with 0 burst time
i++;
for (j = i+1; j < n; j++) {
if (p[j].burst_time <= time - p[i].burst_time) {
p[j].waiting_time = time - p[j].burst_time;
p[j].turn_around_time = p[j].burst_time + p[j].waiting_time;
total_waiting_time += p[j].waiting_time;
total_turn_around_time += p[j].turn_around_time;
printf("%d\t%d\t\t%d\t\t%d\n", p[j].pid, p[j].burst_time, p[j].waiting_time, p[j].turn_around_time);
p[j].burst_time = 0; // set burst time to 0 to skip this process further on
}
}
p[i].waiting_time = time;
p[i].turn_around_time = p[i].burst_time + p[i].waiting_time;
total_waiting_time += p[i].waiting_time;
total_turn_around_time += p[i].turn_around_time;
printf("%d\t%d\t\t%d\t\t%d\n", p[i].pid, p[i].burst_time, p[i].waiting_time, p[i].turn_around_time);
p[i].burst_time = 0; // set burst time to 0 to skip this process further on
time += p[i].turn_around_time;
}
printf("Average waiting time = %.2f\n", (float) total_waiting_time / n);
printf("Average turnaround time = %.2f\n", (float) total_turn_around_time / n);
}
void main() {
process p[5] = {{1, 3, 0}, {2, 1, 0}, {3, 4, 0}, {4, 2, 0}, {5, 5, 0}};
non_preemptive_sjf(p, 5);
}
```
该程序首先定义了一个进程结构体 `Process` 用来存储进程的信息,比如编号(pid)、执行时间(burst_time)、等待时间(waiting_time)和周转时间(turn_around_time)。
在 `sort()` 函数中,对进程按照执行时间进行排序。
在 `non_preemptive_sjf()` 函数中,通过对进程的循环遍历及其相关判断逻辑实现了非抢占式短进程优先调度算法。最终输出比较关键的指标:平均等待时间和平均周转时间。
在 `main()` 函数中,定义了一个进程数组 `p` 并调用 `non_preemptive_sjf()` 函数完成算法的执行。
阅读全文