短作业优先算法完整代码C语言
时间: 2024-06-21 07:02:08 浏览: 166
短作业优先算法代码(C#)
5星 · 资源好评率100%
短作业优先(Shortest Job First, SJF)算法是一种在单个处理器调度中常用的作业调度策略。它优先处理最短的作业,这样可以更快地响应和减少平均周转时间。以下是一个简单的C语言实现,使用链表表示作业队列:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 作业结构体
typedef struct Job {
int id;
int burst_time; // 作业运行所需的时间
struct Job* next;
} Job;
// 初始化链表
Job* initQueue() {
Job* queue = (Job*)malloc(sizeof(Job));
queue->id = 0;
queue->burst_time = 0;
queue->next = NULL;
return queue;
}
// 添加作业到链表
void addJob(Job* queue, int id, int burst_time) {
Job* newNode = (Job*)malloc(sizeof(Job));
newNode->id = id;
newNode->burst_time = burst_time;
newNode->next = queue->next;
queue->next = newNode;
}
// 比较作业的大小并进行调度
int compareJobs(Job* job1, Job* job2) {
return job1->burst_time < job2->burst_time;
}
// 执行SJF调度
void sjfScheduler(Job* queue) {
if (queue == NULL) return;
Job* currentJob = queue;
Job* minJob = queue;
while (currentJob != NULL) {
if (compareJobs(currentJob, minJob)) {
minJob = currentJob;
}
currentJob = currentJob->next;
}
printf("Current job: %d, Burst time: %d\n", minJob->id, minJob->burst_time);
// 假设执行了minJob,然后更新链表
queue->next = minJob->next;
free(minJob);
}
// 主函数
int main() {
srand(time(0)); // 为了示例随机生成作业
Job* queue = initQueue();
int numJobs, i;
printf("Enter number of jobs: ");
scanf("%d", &numJobs);
for (i = 0; i < numJobs; i++) {
int id, burstTime;
printf("Enter job %d ID and burst time: ", i + 1);
scanf("%d %d", &id, &burstTime);
addJob(queue, id, burstTime);
}
sjfScheduler(queue);
return 0;
}
阅读全文