-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrr.cpp
More file actions
139 lines (115 loc) · 3.04 KB
/
rr.cpp
File metadata and controls
139 lines (115 loc) · 3.04 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
/*
Title: Round Robin CPU Scheduling (with Arrival Time)
Description: Simple implementation of Round Robin scheduling using arrival time and a ready queue.
Time Complexity: O(n * m)
Space Complexity: O(n)
*/
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct Process
{
int pid, at, bt, rt, wt, tat;
};
void printGantt(const vector<int> &gantt, const vector<int> &time)
{
cout << "\nGantt Chart:\n ";
for (int pid : gantt)
cout << "| P" << pid << " ";
cout << "|\n";
cout << time[0];
for (int i = 1; i < time.size(); i++)
cout << " " << time[i];
cout << "\n";
}
int main()
{
int n, quantum;
cout << "Enter number of processes: ";
cin >> n;
vector<Process> p(n);
for (int i = 0; i < n; i++)
{
p[i].pid = i + 1;
cout << "\nEnter details for Process " << p[i].pid << "\n";
cout << "Arrival Time: ";
cin >> p[i].at;
cout << "Burst Time: ";
cin >> p[i].bt;
p[i].rt = p[i].bt;
p[i].wt = p[i].tat = 0;
}
cout << "Enter Time Quantum: ";
cin >> quantum;
queue<int> q;
vector<int> gantt, time(1, 0);
int completed = 0, t = 0;
vector<bool> inQ(n, false);
for (int i = 0; i < n; i++)
{
if (p[i].at == 0)
{
q.push(i);
inQ[i] = true;
}
}
while (completed < n)
{
// if queue empty → jump to next arrival
if (q.empty())
{
int next = INT_MAX;
for (int i = 0; i < n; i++)
if (p[i].rt > 0)
next = min(next, p[i].at);
t = next;
time.push_back(t);
gantt.push_back(0); // idle
for (int i = 0; i < n; i++)
if (!inQ[i] && p[i].at <= t)
{
q.push(i);
inQ[i] = true;
}
continue;
}
int i = q.front();
q.pop();
gantt.push_back(p[i].pid);
int run = min(quantum, p[i].rt);
p[i].rt -= run;
t += run;
// push arrivals that came during run
for (int j = 0; j < n; j++)
if (!inQ[j] && p[j].at <= t)
{
q.push(j);
inQ[j] = true;
}
if (p[i].rt > 0)
q.push(i); // not finished
else
{
completed++;
p[i].tat = t - p[i].at;
p[i].wt = p[i].tat - p[i].bt;
}
time.push_back(t);
}
// Result table
cout << "\n--- Round Robin Scheduling ---\n";
cout << "PID\tAT\tBT\tWT\tTAT\n";
float totalWT = 0, totalTAT = 0;
for (auto &x : p)
{
cout << "P" << x.pid << "\t" << x.at << "\t" << x.bt
<< "\t" << x.wt << "\t" << x.tat << "\n";
totalWT += x.wt;
totalTAT += x.tat;
}
cout << "Average Waiting Time = " << totalWT / n << "\n";
cout << "Average Turnaround Time = " << totalTAT / n << "\n";
printGantt(gantt, time);
return 0;
}