3
1
SystemsProgrammingAndOperat.../Codes/Group B/Assignment - 5/Round Robin (Preemptive).cpp

110 lines
3.4 KiB
C++

#include<iostream>
#include<queue>
using namespace std;
struct Process{
int id, burst, arrival, remaining, completion, waiting, turnaround, response;
};
Process processes[30];
class RoundRobin{
public:
int n, timeQuantum;
void input(){
cout<<"\nEnter number of processes: ";
cin>>n;
for(int i = 0; i < n; i++){
cout<<"\nEnter arrival time of P"<<i<<": ";
cin>>processes[i].arrival;
cout<<"Enter burst time of P"<<i<<": ";
cin>>processes[i].burst;
processes[i].id = i;
processes[i].remaining = processes[i].burst;
processes[i].response = -1;
}
cout<<"\nEnter time quantum: ";
cin>>timeQuantum;
}
void process(){
int currentTime = 0;
queue<int> q;
bool inQueue[30] = {false};
int completedProcesses = 0;
for(int i = 0; i < n; i++){
if(processes[i].arrival <= currentTime){
q.push(i);
inQueue[i] = true;
}
}
while(completedProcesses < n){
if(q.empty()){
currentTime++;
for(int i = 0; i < n; i++){
if(!inQueue[i] && processes[i].arrival <= currentTime){
q.push(i);
inQueue[i] = true;
}
}
continue;
}
int idx = q.front();
q.pop();
if(processes[idx].response == -1){
processes[idx].response = currentTime - processes[idx].arrival;
}
if(processes[idx].remaining <= timeQuantum){
currentTime += processes[idx].remaining;
processes[idx].remaining = 0;
processes[idx].completion = currentTime;
processes[idx].turnaround = processes[idx].completion - processes[idx].arrival;
processes[idx].waiting = processes[idx].turnaround - processes[idx].burst;
completedProcesses++;
}else{
currentTime += timeQuantum;
processes[idx].remaining -= timeQuantum;
}
for(int i = 0; i < n; i++){
if(!inQueue[i] && processes[i].arrival <= currentTime && processes[i].remaining > 0){
q.push(i);
inQueue[i] = true;
}
}
if(processes[idx].remaining > 0){
q.push(idx);
}
}
}
void displayMetrics(){
double totalWaiting = 0, totalTurnaround = 0, totalCompletion = 0;
cout<<"\n\n | Completion time | Waiting time | Turnaround time | Response time\n";
for(int i = 0; i < n; i++){
totalWaiting += processes[i].waiting;
totalTurnaround += processes[i].turnaround;
totalCompletion += processes[i].completion;
cout<<"P"<< processes[i].id<<" | "<<processes[i].completion<<" | "<< processes[i].waiting<<" | "<<processes[i].turnaround<<" | "<<processes[i].response<<"\n";
}
cout<<"\nAverage completion time: "<<totalCompletion/n;
cout<<"\nAverage waiting time: "<<totalWaiting/n;
cout<<"\nAverage turnaround time: "<<totalTurnaround/n;
}
};
int main(){
RoundRobin rr;
rr.input();
rr.process();
rr.displayMetrics();
return 0;
}