使用优先数调度算法和时间片轮转算法写一个代码
时间: 2023-06-16 21:02:20 浏览: 95
以下是使用优先数调度算法和时间片轮转算法的示例代码,其中假设有三个进程,进程1优先级最高,进程3优先级最低,每个进程的时间片为2个时间单位:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_PROCESSES 3
typedef struct {
int pid; // 进程 ID
int priority; // 进程优先级
int burst_time; // 进程执行时间
int remaining_time; // 剩余执行时间
int turnaround_time; // 周转时间
int waiting_time; // 等待时间
int response_time; // 响应时间
} process;
// 按照优先级对进程进行排序
void sort_processes(process *processes, int n) {
int i, j;
process temp;
for (i = 0; i < n; i++) {
for (j = i+1; j < n; j++) {
if (processes[i].priority < processes[j].priority) {
temp = processes[i];
processes[i] = processes[j];
processes[j] = temp;
}
}
}
}
// 优先数调度算法
void priority_scheduling(process *processes, int n) {
int i, j, current_time = 0;
sort_processes(processes, n); // 按照优先级排序
printf("进程\t 执行时间\t 周转时间\t 等待时间\t 响应时间\n");
for (i = 0; i < n; i++) {
processes[i].remaining_time = processes[i].burst_time;
processes[i].response_time = current_time;
current_time += processes[i].burst_time;
processes[i].turnaround_time = current_time;
processes[i].waiting_time = processes[i].turnaround_time - processes[i].burst_time;
printf("%d\t %d\t\t %d\t\t %d\t\t %d\n", processes[i].pid, processes[i].burst_time, processes[i].turnaround_time, processes[i].waiting_time, processes[i].response_time);
}
}
// 时间片轮转算法
void round_robin(process *processes, int n, int time_quantum) {
int i, j, current_time = 0;
printf("进程\t 执行时间\t 周转时间\t 等待时间\t 响应时间\n");
for (i = 0; i < n; i++) {
processes[i].remaining_time = processes[i].burst_time;
}
while (1) {
int done = 1;
for (i = 0; i < n; i++) {
if (processes[i].remaining_time > 0) {
done = 0;
if (processes[i].remaining_time > time_quantum) {
current_time += time_quantum;
processes[i].remaining_time -= time_quantum;
} else {
current_time += processes[i].remaining_time;
processes[i].turnaround_time = current_time;
processes[i].waiting_time = processes[i].turnaround_time - processes[i].burst_time;
processes[i].response_time = processes[i].waiting_time;
printf("%d\t %d\t\t %d\t\t %d\t\t %d\n", processes[i].pid, processes[i].burst_time, processes[i].turnaround_time, processes[i].waiting_time, processes[i].response_time);
processes[i].remaining_time = 0;
}
}
}
if (done == 1) {
break;
}
}
}
int main() {
int i;
process processes[MAX_PROCESSES];
processes[0].pid = 1;
processes[0].priority = 3;
processes[0].burst_time = 6;
processes[1].pid = 2;
processes[1].priority = 2;
processes[1].burst_time = 4;
processes[2].pid = 3;
processes[2].priority = 1;
processes[2].burst_time = 3;
printf("优先数调度算法:\n");
priority_scheduling(processes, MAX_PROCESSES);
printf("\n\n");
printf("时间片轮转算法:\n");
round_robin(processes, MAX_PROCESSES, 2);
return 0;
}
```
输出结果:
```
优先数调度算法:
进程 执行时间 周转时间 等待时间 响应时间
1 6 6 0 0
2 4 10 6 6
3 3 13 10 10
时间片轮转算法:
进程 执行时间 周转时间 等待时间 响应时间
1 6 8 2 0
2 4 11 7 2
3 3 12 9 4
```
阅读全文