设计一个按先来先服务,算法时间片轮转法,优先数调度算法实现处理器调度的程序。
时间: 2024-02-01 09:14:18 浏览: 35
以下是一个简单的处理器调度程序,实现了三种调度算法:先来先服务、时间片轮转法、优先数调度算法。
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_PROCESS 10 // 最大进程数
#define TIME_SLICE 2 // 时间片长度
// 进程结构体
typedef struct process {
int pid; // 进程ID
int burst; // 执行时间
int priority; // 优先级
} Process;
// 定义进程队列
Process queue[MAX_PROCESS];
int n = 0; // 进程数
// 添加进程到队列
void add_process(int pid, int burst, int priority) {
if (n >= MAX_PROCESS) {
printf("队列已满,不能添加新进程!\n");
return;
}
queue[n].pid = pid;
queue[n].burst = burst;
queue[n].priority = priority;
n++;
}
// 先来先服务调度算法
void fcfs() {
int i, time = 0;
printf("先来先服务调度算法:\n");
for (i = 0; i < n; i++) {
printf("进程%d运行中...\n", queue[i].pid);
time += queue[i].burst;
}
printf("所有进程执行完毕,总时间为%d个单位时间。\n", time);
}
// 时间片轮转调度算法
void rr() {
int i, time = 0;
printf("时间片轮转调度算法:\n");
while (1) {
for (i = 0; i < n; i++) {
if (queue[i].burst > 0) {
printf("进程%d运行中...\n", queue[i].pid);
queue[i].burst -= TIME_SLICE;
time += TIME_SLICE;
if (queue[i].burst <= 0) {
printf("进程%d执行完毕。\n", queue[i].pid);
}
}
}
int flag = 1;
for (i = 0; i < n; i++) {
if (queue[i].burst > 0) {
flag = 0;
break;
}
}
if (flag) {
break;
}
}
printf("所有进程执行完毕,总时间为%d个单位时间。\n", time);
}
// 优先数调度算法
void priority() {
int i, time = 0;
printf("优先数调度算法:\n");
while (1) {
// 找到优先级最高的进程
int high_priority = -1, high_priority_index = -1;
for (i = 0; i < n; i++) {
if (queue[i].burst > 0 && queue[i].priority > high_priority) {
high_priority = queue[i].priority;
high_priority_index = i;
}
}
if (high_priority_index == -1) {
break;
}
printf("进程%d运行中...\n", queue[high_priority_index].pid);
queue[high_priority_index].burst--;
time++;
if (queue[high_priority_index].burst <= 0) {
printf("进程%d执行完毕。\n", queue[high_priority_index].pid);
}
}
printf("所有进程执行完毕,总时间为%d个单位时间。\n", time);
}
int main() {
add_process(1, 5, 2);
add_process(2, 2, 1);
add_process(3, 4, 3);
fcfs();
rr();
priority();
return 0;
}
```
以上代码中,我们定义了一个 `Process` 结构体来表示进程,包含进程ID、执行时间和优先级三个属性。我们使用一个 `queue` 数组来保存进程队列,使用 `n` 变量来记录当前队列中已有的进程数。`add_process` 函数用来向队列中添加进程。
我们实现了三个调度算法,分别是先来先服务调度算法(`fcfs` 函数)、时间片轮转调度算法(`rr` 函数)和优先数调度算法(`priority` 函数)。
在 `fcfs` 函数中,我们简单地按照队列中进程的顺序执行,将每个进程的执行时间累加到总时间中即可。
在 `rr` 函数中,我们使用了时间片轮转调度算法,每次执行一个时间片(长度为 `TIME_SLICE`),如果进程还未执行完,则继续执行下一个时间片,直到所有进程都执行完毕。
在 `priority` 函数中,我们使用了优先数调度算法,每次选择优先级最高的进程执行,直到所有进程都执行完毕。
在 `main` 函数中,我们添加了三个测试进程,并依次调用三个调度算法进行测试。