-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslip21_2.c
More file actions
78 lines (76 loc) · 2.43 KB
/
slip21_2.c
File metadata and controls
78 lines (76 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_PROCESSES 10
typedef struct {
int arrival_time;
int burst_time;
int priority;
int waiting_time;
int turnaround_time;
} Process;
void generate_next_burst(Process *p) {
p->burst_time = rand() % 10 + 1;
}
void preemptive_priority_scheduling(Process p[], int n) {
int current_time = 0;
int i, j;
Process temp;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (p[i].arrival_time > p[j].arrival_time || (p[i].arrival_time == p[j].arrival_time && p[i].priority < p[j].priority)) {
temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
printf("Gantt Chart:\n");
for (i = 0; i < n; i++) {
printf("P%d | ", i);
while (p[i].burst_time > 0) {
current_time++;
p[i].burst_time--;
printf("%d ", current_time);
if (p[i].burst_time == 0) {
p[i].turnaround_time = current_time - p[i].arrival_time;
p[i].waiting_time = p[i].turnaround_time - p[i].burst_time;
printf("| ");
}
for (j = i + 1; j < n; j++) {
if (p[j].arrival_time <= current_time && p[j].priority > p[i].priority) {
temp = p[i];
p[i] = p[j];
p[j] = temp;
i--;
break;
}
}
}
printf("\n");
}
printf("Process\tTurnaround Time\tWaiting Time\n");
for (i = 0; i < n; i++) {
printf("P%d\t%d\t\t%d\n", i, p[i].turnaround_time, p[i].waiting_time);
}
int total_turnaround_time = 0, total_waiting_time = 0;
for (i = 0; i < n; i++) {
total_turnaround_time += p[i].turnaround_time;
total_waiting_time += p[i].waiting_time;
}
printf("Average Turnaround Time: %.2f\n", (float)total_turnaround_time / n);
printf("Average Waiting Time: %.2f\n", (float)total_waiting_time / n);
}
int main() {
int n;
printf("Enter the number of processes: ");
scanf("%d", &n);
Process p[n];
for (int i = 0; i < n; i++) {
printf("Enter arrival time, burst time, and priority for process P%d: ", i);
scanf("%d %d %d", &p[i].arrival_time, &p[i].burst_time, &p[i].priority);
}
srand(time(NULL));
preemptive_priority_scheduling(p, n);
return 0;
}