用C语言实现RR算法,每个进程由一个进程控制块(PCB)表示,进程控制块包含进程名、到达时间、完成时间、需要运行时间、已用CPU时间、周转时间、带权周转时间、进程状态
时间: 2023-10-03 21:07:19 浏览: 154
以下是用C语言实现RR算法的代码,涉及到进程控制块的定义和使用:
```c
#include <stdio.h>
#define MAX_PROCESSES 10
// 进程状态
typedef enum {
READY,
RUNNING,
FINISHED
} process_state;
// 进程控制块
typedef struct {
char name[10]; // 进程名
int arrival_time; // 到达时间
int finish_time; // 完成时间
int burst_time; // 需要运行时间
int used_time; // 已用CPU时间
int turnaround_time;// 周转时间
float weighted_turnaround_time; // 带权周转时间
process_state state;// 进程状态
} process_control_block;
int main() {
int i, j, quantum, num_processes, time;
float avg_turnaround_time = 0.0, avg_weighted_turnaround_time = 0.0;
process_control_block processes[MAX_PROCESSES];
// 输入进程数和时间片长度
printf("Enter the number of processes: ");
scanf("%d", &num_processes);
printf("Enter the time quantum: ");
scanf("%d", &quantum);
// 输入每个进程的信息
for(i = 0; i < num_processes; i++) {
printf("Enter process name, arrival time and burst time: ");
scanf("%s %d %d", processes[i].name, &processes[i].arrival_time, &processes[i].burst_time);
processes[i].state = READY;
processes[i].used_time = 0;
processes[i].turnaround_time = 0;
processes[i].weighted_turnaround_time = 0.0;
}
// 运行进程
time = 0;
while(1) {
int all_finished = 1;
for(i = 0; i < num_processes; i++) {
if(processes[i].state == READY) {
all_finished = 0;
if(processes[i].burst_time - processes[i].used_time > quantum) {
// 分配时间片
time += quantum;
processes[i].used_time += quantum;
} else {
// 运行完成
time += processes[i].burst_time - processes[i].used_time;
processes[i].used_time = processes[i].burst_time;
processes[i].finish_time = time;
processes[i].turnaround_time = processes[i].finish_time - processes[i].arrival_time;
processes[i].weighted_turnaround_time = (float)processes[i].turnaround_time / processes[i].burst_time;
processes[i].state = FINISHED;
}
}
}
if(all_finished) break;
}
// 输出每个进程的信息
printf("\nProcess\tArrival Time\tBurst Time\tFinish Time\tTurnaround Time\tWeighted Turnaround Time\n");
for(i = 0; i < num_processes; i++) {
printf("%s\t%d\t\t%d\t\t%d\t\t%d\t\t%.2f\n", processes[i].name, processes[i].arrival_time, processes[i].burst_time, processes[i].finish_time, processes[i].turnaround_time, processes[i].weighted_turnaround_time);
avg_turnaround_time += processes[i].turnaround_time;
avg_weighted_turnaround_time += processes[i].weighted_turnaround_time;
}
avg_turnaround_time /= num_processes;
avg_weighted_turnaround_time /= num_processes;
printf("Average Turnaround Time: %.2f\n", avg_turnaround_time);
printf("Average Weighted Turnaround Time: %.2f\n", avg_weighted_turnaround_time);
return 0;
}
```
该程序通过循环遍历进程列表,对于处于 READY 状态的进程,采用时间片轮转的方式分配 CPU 时间,直到进程运行完成。在运行完成后,计算出进程的周转时间和带权周转时间,并输出每个进程的信息以及平均周转时间和带权周转时间。
阅读全文