帮我写时间片轮转调度算法和静态优先级调度算法,可自定义时间片的大小优,先级高低可自定义。的C语言代码
时间: 2024-03-18 22:39:14 浏览: 91
好的,下面是时间片轮转调度算法和静态优先级调度算法的C语言代码实现。
时间片轮转调度算法:
```c
#include <stdio.h>
struct process {
int pid;
int burst_time;
int remaining_time;
};
typedef struct process Process;
void rr_schedule(Process processes[], int n, int time_slice) {
int current_time = 0;
int i, j, k;
int queue[n];
int front = 0;
int rear = -1;
for (i = 0; i < n; i++) {
queue[++rear] = i;
}
while (front <= rear) {
i = queue[front];
front++;
if (processes[i].remaining_time > time_slice) {
current_time += time_slice;
processes[i].remaining_time -= time_slice;
queue[++rear] = i;
} else {
current_time += processes[i].remaining_time;
processes[i].remaining_time = 0;
processes[i].waiting_time = current_time - processes[i].burst_time;
}
}
}
int main() {
int n = 5;
Process processes[] = {{1, 10, 10},
{2, 5, 5},
{3, 8, 8},
{4, 12, 12},
{5, 3, 3}};
int time_slice = 2;
rr_schedule(processes, n, time_slice);
printf("PID\tBurst Time\tWaiting Time\n");
for (int i = 0; i < n; i++) {
printf("%d\t%d\t\t%d\n", processes[i].pid, processes[i].burst_time, processes[i].waiting_time);
}
return 0;
}
```
静态优先级调度算法:
```c
#include <stdio.h>
struct process {
int pid;
int burst_time;
int priority;
};
typedef struct process Process;
void priority_schedule(Process processes[], int n, int priority_levels[]) {
int current_time = 0;
int i, j, k;
for (i = 0; i < n; i++) {
int max_priority = -1;
int selected_process = -1;
for (j = 0; j < n; j++) {
if (processes[j].priority > max_priority && processes[j].burst_time != 0) {
for (k = 0; k < sizeof(priority_levels) / sizeof(priority_levels[0]); k++) {
if (processes[j].priority == priority_levels[k]) {
max_priority = processes[j].priority;
selected_process = j;
break;
}
}
}
}
current_time += processes[selected_process].burst_time;
processes[selected_process].waiting_time = current_time - processes[selected_process].burst_time;
processes[selected_process].burst_time = 0;
}
}
int main() {
int n = 5;
Process processes[] = {{1, 10, 3},
{2, 5, 2},
{3, 8, 4},
{4, 12, 1},
{5, 3, 5}};
int priority_levels[] = {5, 4, 3, 2, 1};
priority_schedule(processes, n, priority_levels);
printf("PID\tBurst Time\tWaiting Time\n");
for (int i = 0; i < n; i++) {
printf("%d\t%d\t\t%d\n", processes[i].pid, processes[i].burst_time, processes[i].waiting_time);
}
return 0;
}
```
其中,Process结构体表示一个进程,包括进程ID(pid)、CPU执行时间(burst_time)和剩余CPU执行时间(remaining_time);rr_schedule函数表示时间片轮转调度算法,包括进程数组(processes)、进程数目(n)和时间片大小(time_slice);priority_schedule函数表示静态优先级调度算法,包括进程数组(processes)、进程数目(n)和优先级级别数组(priority_levels)。
需要注意的是,这里的代码仅供参考,实际应用中可能需要根据具体情况进行修改。
阅读全文