Untitled
unknown
plain_text
9 months ago
3.4 kB
4
Indexable
#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
using namespace std;
struct Process {
int id, at, bt, priority, rt, ct = 0, tat = 0, wt = 0, preempt = 0;
};
// Sort processes by Arrival Time (AT)
bool sortByArrival(Process a, Process b) {
return a.at < b.at;
}
void preemptivePriorityScheduling(vector<Process> &p) {
int n = p.size();
int completed = 0, currentTime = 0, prevProcess = -1;
float totalTAT = 0, totalWT = 0;
vector<int> ganttChart;
for (auto &proc : p) proc.rt = proc.bt; // Initialize remaining times
while (completed < n) {
int idx = -1, minPriority = 1e9;
// Select the highest priority process (lower number = higher priority)
for (int i = 0; i < n; i++) {
if (p[i].at <= currentTime && p[i].rt > 0 && p[i].priority < minPriority) {
minPriority = p[i].priority;
idx = i;
}
}
if (idx == -1) {
ganttChart.push_back(-1); // Idle time
currentTime++;
continue;
}
// If the process is preempted
if (prevProcess != -1 && prevProcess != p[idx].id) {
p[idx].preempt++;
}
ganttChart.push_back(p[idx].id); // Track execution order
prevProcess = p[idx].id;
p[idx].rt--; // Reduce remaining time
currentTime++;
if (p[idx].rt == 0) { // Process completes
completed++;
p[idx].ct = currentTime;
p[idx].tat = p[idx].ct - p[idx].at;
p[idx].wt = p[idx].tat - p[idx].bt;
totalTAT += p[idx].tat;
totalWT += p[idx].wt;
}
}
// Print process table
cout << "\nProcess Table:\n";
cout << "-----------------------------------------------------------\n";
cout << "PID\tAT\tBT\tPriority\tCT\tTAT\tWT\tPreempt\n";
cout << "-----------------------------------------------------------\n";
for (const auto &proc : p) {
cout << proc.id << "\t" << proc.at << "\t" << proc.bt << "\t"
<< proc.priority << "\t\t" << proc.ct << "\t" << proc.tat
<< "\t" << proc.wt << "\t" << proc.preempt << endl;
}
cout << "\nAverage Turnaround Time: " << totalTAT / n;
cout << "\nAverage Waiting Time: " << totalWT / n << endl;
// Print Gantt Chart
cout << "\nGantt Chart:\n--------------------------------------------------\n";
for (size_t i = 0; i < ganttChart.size(); i++) {
if (i == 0 || ganttChart[i] != ganttChart[i - 1])
cout << "| P" << ganttChart[i] << " ";
}
cout << "|\n--------------------------------------------------\n0 ";
for (size_t i = 1; i <= ganttChart.size(); i++) {
if (i == ganttChart.size() || ganttChart[i] != ganttChart[i - 1])
cout << i << " ";
}
cout << endl;
}
int main() {
int n;
cout << "Enter number of processes: ";
cin >> n;
vector<Process> p(n);
cout << "Enter Arrival Time, Burst Time, and Priority (lower is higher priority):\n";
for (int i = 0; i < n; i++) {
p[i].id = i + 1;
cin >> p[i].at >> p[i].bt >> p[i].priority;
}
// Sort processes by arrival time
sort(p.begin(), p.end(), sortByArrival);
// Run Scheduling
preemptivePriorityScheduling(p);
return 0;
}Editor is loading...
Leave a Comment