单处理机系统的进程调度C语言实验代码
时间: 2023-10-21 19:06:15 浏览: 116
以下是一个简单的单处理机系统进程调度的C语言实验代码:
#include <stdio.h>
#include <stdlib.h>
// 进程结构体
typedef struct Process {
int pid; // 进程ID
int priority; // 进程优先级
int burstTime; // 进程执行时间
int remainingTime; // 进程剩余执行时间
} Process;
// 初始化进程
void initProcess(Process *process, int pid, int priority, int burstTime) {
process->pid = pid;
process->priority = priority;
process->burstTime = burstTime;
process->remainingTime = burstTime;
}
// 进程比较函数,按照优先级从大到小排序
int compareProcess(const void *a, const void *b) {
Process *processA = (Process *)a;
Process *processB = (Process *)b;
return processB->priority - processA->priority;
}
int main() {
int n; // 进程数
printf("请输入进程数:");
scanf("%d", &n);
Process *processes = (Process *)malloc(n * sizeof(Process)); // 动态分配进程数组内存
// 初始化进程
for (int i = 0; i < n; i++) {
int pid, priority, burstTime;
printf("请输入进程 %d 的ID、优先级和执行时间(以空格分隔):", i + 1);
scanf("%d%d%d", &pid, &priority, &burstTime);
initProcess(&processes[i], pid, priority, burstTime);
}
qsort(processes, n, sizeof(Process), compareProcess); // 按照优先级排序
int currentTime = 0; // 当前时间
int totalWaitingTime = 0; // 总等待时间
int totalTurnaroundTime = 0; // 总周转时间
printf("进程执行顺序:");
for (int i = 0; i < n; i++) {
printf("%d ", processes[i].pid);
totalWaitingTime += currentTime; // 累加等待时间
currentTime += processes[i].burstTime; // 更新当前时间
totalTurnaroundTime += currentTime; // 累加周转时间
}
printf("\n平均等待时间:%.2f\n", (float)totalWaitingTime / n);
printf("平均周转时间:%.2f\n", (float)totalTurnaroundTime / n);
free(processes); // 释放进程数组内存
return 0;
}
阅读全文