动态优先权调度算法c++
时间: 2023-10-18 08:01:51 浏览: 152
以下是一个基于动态优先权调度算法的C语言代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_PROCESS 10
typedef struct process {
int pid; // 进程ID
int arrival_time; // 到达时间
int burst_time; // 执行时间
int priority; // 优先级
int waiting_time; // 等待时间
int turnaround_time; // 周转时间
} process;
int main() {
int n, i, j, time = 0, total_waiting_time = 0, total_turnaround_time = 0;
float avg_waiting_time, avg_turnaround_time;
process p[MAX_PROCESS], temp;
printf("Enter the number of processes: ");
scanf("%d", &n);
printf("Enter the arrival time, burst time and priority for each process:\n");
for (i = 0; i < n; i++) {
p[i].pid = i + 1;
scanf("%d %d %d", &p[i].arrival_time, &p[i].burst_time, &p[i].priority);
}
// Sort the processes based on their arrival time
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (p[i].arrival_time > p[j].arrival_time) {
temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
// Execute the processes in order of their priority
for (i = 0; i < n; i++) {
// Find the process with the highest priority that has arrived
int highest_priority_index = -1;
for (j = 0; j < n; j++) {
if (p[j].arrival_time <= time && p[j].burst_time > 0) {
if (highest_priority_index == -1 || p[j].priority < p[highest_priority_index].priority) {
highest_priority_index = j;
}
}
}
// Execute the process
p[highest_priority_index].burst_time--;
time++;
// Update waiting and turnaround time for all processes
for (j = 0; j < n; j++) {
if (p[j].arrival_time <= time && p[j].burst_time > 0) {
if (j != highest_priority_index) {
p[j].waiting_time++;
}
p[j].turnaround_time++;
}
}
}
// Calculate waiting and turnaround time for each process
for (i = 0; i < n; i++) {
total_waiting_time += p[i].waiting_time;
total_turnaround_time += p[i].turnaround_time;
}
avg_waiting_time = (float)total_waiting_time / n;
avg_turnaround_time = (float)total_turnaround_time / n;
// Print the results
printf("Process\tArrival Time\tBurst Time\tPriority\tWaiting Time\tTurnaround Time\n");
for (i = 0; i < n; i++) {
printf("%d\t%d\t\t%d\t\t%d\t\t%d\t\t%d\n", p[i].pid, p[i].arrival_time, p[i].burst_time + 1, p[i].priority, p[i].waiting_time, p[i].turnaround_time + 1);
}
printf("Average waiting time: %f\n", avg_waiting_time);
printf("Average turnaround time: %f\n", avg_turnaround_time);
return 0;
}
```
该代码实现了动态优先权调度算法,并计算每个进程的等待时间和周转时间,以及所有进程的平均等待时间和平均周转时间。在执行过程中,它会按照进程的到达时间排序,然后执行具有最高优先级的进程。每次执行完一个时间片后,它会更新每个进程的等待时间和周转时间。最后,它会输出每个进程的详细信息和平均等待时间和平均周转时间。
阅读全文