Comprehending the Objective
I'm now fully immersed in understanding the user's objective – a process scheduler implemented in code. This initial phase is crucial. Delving into the user's explicit and implicit expectations will shape the subsequent design decisions. I've begun to consider the various real-world constraints this scheduler must handle.
Formulating Core Elements
I'm now identifying the key components of the scheduler. It's becoming clearer I'll need a Process Control Block, a Ready Queue, a Scheduler Core, and a Simulation Loop, alongside the scheduling policies. C++ is the leading choice for this project, with its robust standard library, its efficiency, and its low-level control. I'm beginning the initial architecture design, including a struct to hold all of a process' attributes.
Designing the Core Scheduler
I'm solidifying the scheduling classes and methods. The Scheduler class will be key, containing addProcess(), run(), and variants for each policy: FCFS, SJF (non-preemptive for now), Round Robin, and Priority. I'll also include calculateMetrics() to measure Waiting Time and Turnaround Time. My mental run-throughs of FCFS, SJF, Round Robin, and Priority are focusing on the intricacies of arrival times and the queue manipulation required by Round Robin.
Expanding SJF and RR
The current focus is on finalizing Shortest Job First and Round Robin. For SJF, I've incorporated the priority comparison for tie-breaking. Round Robin's simulation approach is proving fruitful: sorting by arrival, managing a queue, and time-stepping through processes handles new arrivals and context switches logically. The details of the Round Robin simulation loop are clearer now. I'm now thinking about the finer points of how a process relinquishes the CPU.
Defining Simulation Loop Details
I'm now fully immersed in the core simulation loops. For Shortest Job First, I'm carefully considering how to iterate through the processes at each time step. The current approach involves checking the current time and filtering the process list based on arrival times. For Round Robin, a std::queue will manage the ready processes, and an index keeps track of newly arrived ones. I am now formalizing the process for how to run and manage the ready queue. The logic is coming together clearly.
Polishing and Presenting
I'm now putting the finishing touches on the scheduler. I'm focusing on adding thorough comments to explain the complex logic, especially around context switching and queue management. Next, I will format the output table using std::setw to ensure it's clean and easy to read. I'm also double-checking the Round Robin implementation to make certain the context switch logic is fully correct, especially ensuring a process is added to the ready queue only after new arrivals have been considered. After this, the project will be ready for final presentation.
This is a C++ implementation of a Process Scheduler simulation. It utilizes a modular design that supports four common scheduling algorithms:
- FCFS (First-Come, First-Served)
- SJF (Shortest Job First - Non-preemptive)
- Priority (Non-preemptive)
- Round Robin (Preemptive with Time Quantum)
The C++ Implementation
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <iomanip>
using namespace std;
struct Process {
int pid; // Process ID
int arrivalTime; // Time process arrives
int burstTime; // CPU time required
int remainingTime; // For Round Robin
int priority; // Lower number = higher priority
int completionTime;
int waitingTime;
int turnaroundTime;
};
// Comparator for sorting by Arrival Time
bool compareArrival(const Process& a, const Process& b) {
return a.arrivalTime < b.arrivalTime;
}
class Scheduler {
private:
vector<Process> processes;
// Helper to reset remaining times before a run
void resetProcesses(vector<Process>& procs) {
for (auto& p : procs) {
p.remainingTime = p.burstTime;
p.completionTime = 0;
p.waitingTime = 0;
p.turnaroundTime = 0;
}
}
void printMetrics(const vector<Process>& procs, string algorithmName) {
cout << "\n=== " << algorithmName << " Results ===\n";
cout << left << setw(10) << "PID"
<< setw(10) << "Arrival"
<< setw(10) << "Burst"
<< setw(10) << "Priority"
<< setw(15) << "Completion"
<< setw(15) << "Turnaround"
<< setw(15) << "Waiting" << endl;
cout << string(85, '-') << endl;
double totalWait = 0, totalTurnaround = 0;
for (const auto& p : procs) {
cout << left << setw(10) << p.pid
<< setw(10) << p.arrivalTime
<< setw(10) << p.burstTime
<< setw(10) << p.priority
<< setw(15) << p.completionTime
<< setw(15) << p.turnaroundTime
<< setw(15) << p.waitingTime << endl;
totalWait += p.waitingTime;
totalTurnaround += p.turnaroundTime;
}
cout << "\nAverage Waiting Time: " << totalWait / procs.size() << endl;
cout << "Average Turnaround Time: " << totalTurnaround / procs.size() << endl;
cout << endl;
}
public:
void addProcess(int id, int arrival, int burst, int priority = 0) {
processes.push_back({id, arrival, burst, burst, priority, 0, 0, 0});
}
// 1. First Come First Serve
void runFCFS() {
vector<Process> localProcs = processes; // Work on a copy
resetProcesses(localProcs);
sort(localProcs.begin(), localProcs.end(), compareArrival);
int currentTime = 0;
for (auto& p : localProcs) {
if (currentTime < p.arrivalTime) {
currentTime = p.arrivalTime; // CPU idle catch-up
}
currentTime += p.burstTime;
p.completionTime = currentTime;
p.turnaroundTime = p.completionTime - p.arrivalTime;
p.waitingTime = p.turnaroundTime - p.burstTime;
}
printMetrics(localProcs, "FCFS");
}
// 2. Shortest Job First (Non-Preemptive)
void runSJF() {
vector<Process> localProcs = processes;
resetProcesses(localProcs);
int currentTime = 0;
int completed = 0;
int n = localProcs.size();
vector<bool> isCompleted(n, false);
// This vector isn't sorted initially; we search for the candidate
while (completed != n) {
int idx = -1;
int minBurst = 1e9;
// Find process with min burst time among arrived processes
for (int i = 0; i < n; i++) {
if (localProcs[i].arrivalTime <= currentTime && !isCompleted[i]) {
if (localProcs[i].burstTime < minBurst) {
minBurst = localProcs[i].burstTime;
idx = i;
}
// If burst times match, FCFS rule applies (usually by lower PID or arrival)
if (localProcs[i].burstTime == minBurst) {
if (localProcs[i].arrivalTime < localProcs[idx].arrivalTime) {
idx = i;
}
}
}
}
if (idx != -1) {
currentTime += localProcs[idx].burstTime;
localProcs[idx].completionTime = currentTime;
localProcs[idx].turnaroundTime = localProcs[idx].completionTime - localProcs[idx].arrivalTime;
localProcs[idx].waitingTime = localProcs[idx].turnaroundTime - localProcs[idx].burstTime;
isCompleted[idx] = true;
completed++;
} else {
currentTime++; // CPU idle
}
}
printMetrics(localProcs, "Shortest Job First (Non-Preemptive)");
}
// 3. Priority Scheduling (Non-Preemptive) - Lower # is higher priority
void runPriority() {
vector<Process> localProcs = processes;
resetProcesses(localProcs);
int currentTime = 0;
int completed = 0;
int n = localProcs.size();
vector<bool> isCompleted(n, false);
while (completed != n) {
int idx = -1;
int highestPriority = 1e9; // Start with very low priority
for (int i = 0; i < n; i++) {
if (localProcs[i].arrivalTime <= currentTime && !isCompleted[i]) {
if (localProcs[i].priority < highestPriority) {
highestPriority = localProcs[i].priority;
idx = i;
}
// Tie-breaker: Arrival time
if (localProcs[i].priority == highestPriority) {
if (localProcs[i].arrivalTime < localProcs[idx].arrivalTime) {
idx = i;
}
}
}
}
if (idx != -1) {
currentTime += localProcs[idx].burstTime;
localProcs[idx].completionTime = currentTime;
localProcs[idx].turnaroundTime = localProcs[idx].completionTime - localProcs[idx].arrivalTime;
localProcs[idx].waitingTime = localProcs[idx].turnaroundTime - localProcs[idx].burstTime;
isCompleted[idx] = true;
completed++;
} else {
currentTime++;
}
}
printMetrics(localProcs, "Priority Scheduling");
}
// 4. Round Robin
void runRoundRobin(int timeQuantum) {
vector<Process> localProcs = processes;
resetProcesses(localProcs);
sort(localProcs.begin(), localProcs.end(), compareArrival); // Needed to push to queue in order
int currentTime = 0;
queue<int> readyQueue; // Stores indices
vector<bool> inQueue(localProcs.size(), false);
int completed = 0;
// Push initially available processes
if (!localProcs.empty()) {
// Only push the first one to start, the loop handles the rest
// (Or handle idle time if first arrives at t=5)
}
int index = 0; // Points to next process to check for arrival
// Logic to start the queue
while(index < localProcs.size() && localProcs[index].arrivalTime <= currentTime) {
readyQueue.push(index);
inQueue[index] = true;
index++;
}
// If queue is empty but processes remain (gap at start)
if(readyQueue.empty() && index < localProcs.size()) {
currentTime = localProcs[index].arrivalTime;
readyQueue.push(index);
inQueue[index] = true;
index++;
}
while (!readyQueue.empty()) {
int idx = readyQueue.front();
readyQueue.pop();
// Execute
int execTime = min(timeQuantum, localProcs[idx].remainingTime);
localProcs[idx].remainingTime -= execTime;
currentTime += execTime;
// Check for new arrivals during this execution
while (index < localProcs.size() && localProcs[index].arrivalTime <= currentTime) {
if (!inQueue[index]) {
readyQueue.push(index);
inQueue[index] = true;
}
index++;
}
// If process finished
if (localProcs[idx].remainingTime == 0) {
localProcs[idx].completionTime = currentTime;
localProcs[idx].turnaroundTime = localProcs[idx].completionTime - localProcs[idx].arrivalTime;
localProcs[idx].waitingTime = localProcs[idx].turnaroundTime - localProcs[idx].burstTime;
completed++;
} else {
// Otherwise, push back to queue
readyQueue.push(idx);
}
// Handle CPU idle case inside loop if queue becomes empty but list isn't done
if (readyQueue.empty() && completed < localProcs.size()) {
// Fast forward to next arrival
// Sort original array to find next closest arrival?
// Since we sorted localProcs at start, just look at index.
if(index < localProcs.size()) {
currentTime = localProcs[index].arrivalTime;
readyQueue.push(index);
inQueue[index] = true;
index++;
}
}
}
// We need to map the sorted local results back to original order or just print directly
// Printing directly is fine
printMetrics(localProcs, "Round Robin (Quantum=" + to_string(timeQuantum) + ")");
}
};
int main() {
Scheduler sched;
// Demo Data: ID, Arrival, Burst, Priority
sched.addProcess(1, 0, 10, 3);
sched.addProcess(2, 0, 1, 1);
sched.addProcess(3, 3, 2, 4);
sched.addProcess(4, 5, 1, 5);
sched.addProcess(5, 10, 5, 2);
cout << "Process Scheduler Simulation" << endl;
sched.runFCFS();
sched.runSJF();
sched.runPriority();
sched.runRoundRobin(2); // Time Quantum = 2
return 0;
}
How it Works
1. Process Control Block (PCB)
The struct Process acts as the PCB. It holds static data (ID, Arrival, Burst, Priority) and dynamic data calculated during simulation (Remaining Time, Waiting Time, Turnaround Time).
2. The Scheduler Class
The class acts as the OS kernel. Since simulation changes the state of processes (like reducing remaining time), the scheduling functions (runFCFS, runSJF, etc.) create a local copy of the process list. This allows you to run multiple simulations on the same dataset without restarting the program.
3. Scheduling Policies
- FCFS: Uses
std::sort to order processes by arrival time. It iterates through them linearly. If the CPU is free but the next process hasn't arrived (currentTime < arrivalTime), the CPU "waits" by advancing currentTime.
- SJF (Non-preemptive): At every step, it looks at the pool of processes that have
arrivalTime <= currentTime but are not yet completed. It selects the one with the lowest burstTime.
- Priority: Works identically to SJF, but it selects based on the
priority integer (where a lower number implies higher importance).
- Round Robin: This is the most complex.
- It utilizes a
std::queue (FIFO) to manage the Ready Queue.
- It keeps an
index pointer on the main list to see which processes just arrived.
- A process runs for
min(quantum, remainingTime).
- Crucial Step: Before putting the current process back into the queue (if it isn't done), we must check if any new processes arrived during the execution time and add them to the queue before adding the current process back. This ensures fairness.
4. Metrics Calculation
- Turnaround Time (TAT): CompletionTime−ArrivalTime
- Waiting Time (WT):
Compilation and execution
To run this code, save it as scheduler.cpp and compile it using:
g++ -o scheduler scheduler.cpp
./scheduler