操作系统进程调度时间片轮转算法c语言
时间: 2023-12-06 12:37:13 浏览: 147
以下是C语言实现时间片轮转调度算法的代码,其中包括了进程结构体定义、进程初始化、时间片轮转调度算法等内容:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_PROCESS_NUM 10 // 最大进程数
#define TIME_QUANTUM 2 // 时间片大小
// 进程结构体定义
typedef struct {
int pid; // 进程ID
int arrival_time; // 到达时间
int burst_time; // 执行时间
int remaining_time; // 剩余执行时间
int turnaround_time; // 周转时间
float weighted_turnaround_time; // 带权周转时间
} Process;
// 进程初始化
void init_processes(Process processes[], int num_processes) {
for (int i = 0; i < num_processes; i++) {
printf("Enter arrival time and burst time for process %d: ", i + 1);
scanf("%d %d", &processes[i].arrival_time, &processes[i].burst_time);
processes[i].pid = i + 1;
processes[i].remaining_time = processes[i].burst_time;
}
}
// 时间片轮转调度算法
void round_robin_scheduling(Process processes[], int num_processes) {
int current_time = 0;
int completed_processes = 0;
int time_quantum_count = 0;
int queue[MAX_PROCESS_NUM];
int front = 0, rear = -1;
// 将所有到达时间小于等于当前时间的进程加入队列
for (int i = 0; i < num_processes; i++) {
if (processes[i].arrival_time <= current_time) {
queue[++rear] = i;
}
}
// 执行时间片轮转调度算法
while (completed_processes < num_processes) {
int current_process = queue[front++]; // 取出队首进程
time_quantum_count = 0; // 时间片计数器清零
// 执行当前进程
printf("Executing process %d from time %d\n", processes[current_process].pid, current_time);
if (processes[current_process].remaining_time <= TIME_QUANTUM) {
current_time += processes[current_process].remaining_time;
processes[current_process].remaining_time = 0;
processes[current_process].turnaround_time = current_time - processes[current_process].arrival_time;
processes[current_process].weighted_turnaround_time = (float) processes[current_process].turnaround_time / processes[current_process].burst_time;
completed_processes++;
} else {
current_time += TIME_QUANTUM;
processes[current_process].remaining_time -= TIME_QUANTUM;
}
// 将所有到达时间小于等于当前时间的进程加入队列
for (int i = 0; i < num_processes; i++) {
if (processes[i].arrival_time <= current_time && processes[i].remaining_time > 0) {
int in_queue = 0;
for (int j = front; j <= rear; j++) {
if (queue[j] == i) {
in_queue = 1;
break;
}
}
if (!in_queue) {
queue[++rear] = i;
}
}
}
// 如果当前进程还有剩余时间,将其重新加入队列
if (processes[current_process].remaining_time > 0) {
queue[++rear] = current_process;
}
}
}
int main() {
int num_processes;
Process processes[MAX_PROCESS_NUM];
printf("Enter the number of processes: ");
scanf("%d", &num_processes);
init_processes(processes, num_processes);
round_robin_scheduling(processes, num_processes);
// 输出每个进程的周转时间和带权周转时间
printf("Process\tTurnaround Time\tWeighted Turnaround Time\n");
for (int i = 0; i < num_processes; i++) {
printf("%d\t%d\t\t%.2f\n", processes[i].pid, processes[i].turnaround_time, processes[i].weighted_turnaround_time);
}
return 0;
}
```
阅读全文