非抢占式时间片轮转算法c语言怎么写
时间: 2024-05-09 18:21:53 浏览: 90
非抢占式时间片轮转算法的C语言实现如下:
```
#include <stdio.h>
struct process {
int pid; // 进程ID
int arrival_time; // 到达时间
int burst_time; // 执行时间
int waiting_time; // 等待时间
int turnaround_time; // 周转时间
int priority; // 优先级
};
void findWaitingTime(struct process proc[], int n, int quantum) {
int remaining_time[n];
int i, time, flag = 0;
for(i = 0; i < n; i++) {
remaining_time[i] = proc[i].burst_time;
}
time = 0;
while(1) {
flag = 0;
for(i = 0; i < n; i++) {
if(remaining_time[i] > 0) {
flag = 1;
if(remaining_time[i] > quantum) {
time += quantum;
remaining_time[i] -= quantum;
} else {
time = time + remaining_time[i];
proc[i].waiting_time = time - proc[i].burst_time;
remaining_time[i] = 0;
}
}
}
if(flag == 0) {
break;
}
}
}
void findTurnaroundTime(struct process proc[], int n) {
int i;
for(i = 0; i < n; i++) {
proc[i].turnaround_time = proc[i].burst_time + proc[i].waiting_time;
}
}
void findavgTime(struct process proc[], int n, int quantum) {
int i, total_waiting_time =0, total_turnaround_time = 0;
findWaitingTime(proc, n, quantum);
findTurnaroundTime(proc, n);
printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time");
for(i=0;i<n;i++) {
total_waiting_time += proc[i].waiting_time;
total_turnaround_time += proc[i].turnaround_time;
printf("\nP%d\t\t%d\t\t%d\t\t%d", proc[i].pid, proc[i].burst_time, proc[i].waiting_time, proc[i].turnaround_time);
}
printf("\n\nAverage Waiting Time = %f", (float)total_waiting_time/n);
printf("\nAverage Turnaround Time = %f", (float)total_turnaround_time/n);
}
int main() {
int i, n, quantum;
struct process proc[20];
printf("Enter the number of processes: ");
scanf("%d", &n);
for(i = 0; i < n; i++) {
printf("\nEnter the arrival time of process %d: ", i+1);
scanf("%d", &proc[i].arrival_time);
printf("Enter the burst time of process %d: ", i+1);
scanf("%d", &proc[i].burst_time);
printf("Enter the priority of process %d: ", i+1);
scanf("%d", &proc[i].priority);
proc[i].pid = i+1;
}
printf("\nEnter the time quantum: ");
scanf("%d", &quantum);
findavgTime(proc, n, quantum);
return 0;
}
```
这段代码是一个基本的非抢占式时间片轮转算法的实现,可以根据输入的进程参数和时间片数量计算出平均等待时间和平均周转时间。需要注意的是,这个实现只适用于单个CPU的情况下,如果有多个CPU,还需要进一步修改实现。
阅读全文