先到先服务调度算法FCFS,作业个数至少3个以上(动态),让用户动态输入,每个作业至少要有作业名、到达时间、估计运行时间等相关信息,使用C语言
时间: 2024-09-29 14:10:40 浏览: 61
先到先服务(First-Come, First-Served, FCFS)是一种基本的作业调度算法,它的核心思想是按照作业到达系统的时间顺序来处理它们,即最先到达的作业会优先得到处理。在C语言中实现这个算法,可以创建一个简单的程序结构,步骤如下:
1. 定义一个作业结构体(Job),包含作业名(job_name)、到达时间(arrival_time)、估计运行时间(estimated_run_time)等字段。
```c
typedef struct {
char job_name[50];
time_t arrival_time;
time_t estimated_run_time;
} Job;
```
2. 创建一个队列来存储作业,这里可以用链表或数组结合栈的数据结构,C标准库里的`stdio.h`库提供的`getc()`函数可以让用户动态输入作业信息。
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct QueueNode {
Job job;
struct QueueNode *next;
} QueueNode;
struct Queue {
QueueNode *front;
QueueNode *rear;
};
```
3. 用户输入部分,使用`scanf`读取作业数据并添加到队列中。
```c
Queue queue;
QueueNode *new_node;
while (1) {
printf("请输入作业名(按q结束):");
char input[50];
fgets(input, sizeof(input), stdin);
if (input[0] == 'q') break;
printf("请输入到达时间(Unix时间戳):");
scanf("%ld", &new_node->job.arrival_time);
printf("请输入估计运行时间(秒):");
scanf("%ld", &new_node->job.estimated_run_time);
// 假设已经有一个空闲节点,如果没有则创建新的节点
if (!queue.front) {
new_node = (QueueNode*)malloc(sizeof(QueueNode));
new_node->job.job_name = input;
queue.front = queue.rear = new_node;
} else {
new_node->job.job_name = input;
queue.rear->next = (QueueNode*)malloc(sizeof(QueueNode));
queue.rear = queue.rear->next;
queue.rear->job = new_job;
}
}
```
4. 实现FCFS调度过程,遍历队列,按到达时间排序,并依次执行作业。
```c
void fcfs(Schedule queue) {
QueueNode *current = queue.front;
while (current != NULL) {
printf("当前执行 %s,到达时间 %ld\n", current->job.job_name, current->job.arrival_time);
// 模拟执行,这里只是一个示例,实际操作中可能需要更复杂的模拟过程
sleep(current->job.estimated_run_time); // 睡眠对应的时间
// 移动指针到下一个作业
current = current->next;
}
}
int main() {
// 初始化队列
queue.front = queue.rear = NULL;
// 开始接受并调度作业
fcfs(queue);
return 0;
}
```
阅读全文
相关推荐

















