When handling ties in priority scheduling, you can use additional criteria to determine the order of processes with the same priority. Common approaches include:
-
First-Come, First-Served (FCFS): If two or more processes have the same priority, the one that arrived first is scheduled first.
-
Shortest Job Next (SJN): Among the processes with the same priority, the one with the shortest burst time is scheduled first.
-
Round Robin: If processes have the same priority, they can be scheduled in a round-robin manner, giving each process a time slice.
Here’s how you can modify the previous C++ implementation to handle ties using the FCFS approach:
#include <iostream>
#include <vector>
#include <algorithm>
struct Process {
int id; // Process ID
int burstTime; // Burst Time
int priority; // Priority
int arrivalTime; // Arrival Time
};
// Function to sort processes based on priority and arrival time
bool compare(Process a, Process b) {
if (a.priority == b.priority) {
return a.arrivalTime < b.arrivalTime; // FCFS for same priority
}
return a.priority < b.priority;
}
// Function to implement Priority Scheduling with tie-breaking
void priorityScheduling(std::vector<Process> &processes) {
// Sort processes by priority and arrival time
std::sort(processes.begin(), processes.end(), compare);
int totalWaitingTime = 0;
int totalTurnaroundTime = 0;
int n = processes.size();
std::cout << "Process ID\tBurst Time\tPriority\tWaiting Time\tTurnaround Time\n";
for (int i = 0; i < n; i++) {
int waitingTime = (i == 0) ? 0 : processes[i - 1].burstTime + totalWaitingTime;
int turnaroundTime = waitingTime + processes[i].burstTime;
totalWaitingTime += waitingTime;
totalTurnaroundTime += turnaroundTime;
std::cout << processes[i].id << "\t\t" << processes[i].burstTime << "\t\t"
<< processes[i].priority << "\t\t" << waitingTime << "\t\t"
<< turnaroundTime << "\n";
}
std::cout << "Average Waiting Time: " << (float)totalWaitingTime / n << "\n";
std::cout << "Average Turnaround Time: " << (float)totalTurnaroundTime / n << "\n";
}
int main() {
std::vector<Process> processes = {
{1, 10, 2, 0},
{2, 5, 1, 1},
{3, 8, 2, 2},
{4, 6, 1, 3}
};
priorityScheduling(processes);
return 0;
}
Key Changes:
- Arrival Time: Added an
arrivalTimefield to theProcessstructure. - Sorting Logic: The
comparefunction now checks for priority first and uses arrival time to break ties. - Example Processes: The
mainfunction includes processes with the same priority but different arrival times.
This implementation will ensure that when two processes have the same priority, the one that arrived first will be scheduled first.
