生成一个c语言写的时间片轮询程序
时间: 2024-05-24 19:12:25 浏览: 107
下面是一个简单的时间片轮询程序,使用C语言编写:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_PROCESSES 5
#define TIME_QUANTUM 5
typedef struct {
int pid;
int arrival_time;
int burst_time;
int remaining_time;
} process_t;
int main() {
process_t processes[MAX_PROCESSES];
int i, total_burst_time = 0;
// 初始化进程
for (i = 0; i < MAX_PROCESSES; i++) {
processes[i].pid = i + 1;
processes[i].arrival_time = rand() % 10; // 随机到达时间在0-9之间
processes[i].burst_time = rand() % 20 + 1; // 随机执行时间在1-20之间
processes[i].remaining_time = processes[i].burst_time; // 剩余执行时间等于总执行时间
total_burst_time += processes[i].burst_time; // 计算所有进程的总执行时间
}
// 时间片轮询
int current_time = 0;
while (total_burst_time > 0) {
for (i = 0; i < MAX_PROCESSES; i++) {
if (processes[i].remaining_time > 0) {
printf("Process %d is running at time %d\n", processes[i].pid, current_time);
if (processes[i].remaining_time > TIME_QUANTUM) {
processes[i].remaining_time -= TIME_QUANTUM;
total_burst_time -= TIME_QUANTUM;
current_time += TIME_QUANTUM;
} else {
total_burst_time -= processes[i].remaining_time;
current_time += processes[i].remaining_time;
processes[i].remaining_time = 0;
}
}
}
}
return 0;
}
阅读全文