Open In App

Preemptive Priority CPU Scheduling Algorithm

Last Updated : 27 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Preemptive Priority CPU Scheduling Algorithm is a pre-emptive method of CPU scheduling algorithm that works based on the priority of a process. In this algorithm, the scheduler schedules the tasks to work as per the priority, which means that a higher priority process should be executed first. In case of any conflict, i.e., when there is more than one process with equal priorities, then the pre-emptive priority CPU scheduling algorithm works on the basis of FCFS (First Come First Serve) algorithm.

How does Preemptive Priority CPU Scheduling Algorithm decide the Priority of a Process?

Preemptive Priority CPU Scheduling Algorithm uses a rank-based system to define a rank for each process, where lower rank processes have higher priority and higher rank processes have lower priority. For instance, if there are 10 processes to be executed using this Preemptive Algorithm, then process with rank 1 will have the highest priority, the process with rank 2 will have comparatively lesser priority, and process with rank 10 will have least priority.  

How does Preemptive Priority CPU Scheduling Algorithm work?

  • Step-1: Select the first process whose arrival time will be 0, we need to select that process because that process is only executing at time t=0.
  • Step-2: Check the priority of the next available process. Here we need to check for 3 conditions.
    • if priority(current_process) > priority(prior_process) :- then execute the current process.
    • if priority(current_process) < priority(prior_process) :- then execute the prior process.
    • if priority(current_process) = priority(prior_process) :- then execute the process which arrives first i.e., arrival time should be first.
  • Step-3: Repeat Step-2 until it reaches the final process.
  • Step-4: When it reaches the final process, choose the process which is having the highest priority & execute it. Repeat the same step until all processes complete their execution.

Program for Preemptive Priority CPU Scheduling

The preemptive Priority algorithm can be implemented using Min Heap data structure. For the detailed implementation of the Preemptive priority scheduling algorithm, please refer: Program for Preemptive Priority CPU Scheduling. 
 

Examples to show the working of Preemptive Priority CPU Scheduling Algorithm

Example-1: Consider the following table of arrival time, Priority, and burst time for five processes P1, P2, P3, P4, and P5. 

ProcessArrival Time PriorityBurst Time
 P1   0 ms33 ms
 P2 1 ms24 ms
 P3 2 ms4   6 ms
 P4 3 ms6   4 ms
 P5 5 ms10   2 ms

The Preemptive Priority CPU Scheduling Algorithm will work on the basis of the steps mentioned below:

  • At time t = 0, 
    • Process P1 is the only process available in the ready queue, as its arrival time is 0ms.
    • Hence Process P1 is executed first for 1ms, from 0ms to 1ms, irrespective of its priority. 
    • Remaining Burst time (B.T) for P1 = 3-1 = 2 ms.
Time InstanceProcessArrival TimePriorityExecution TimeInitial Burst TimeFinal Burst Time
0 ms – 1 ms P1   0 ms31ms3 ms2 ms
  • At time t = 1 ms, 
    • There are 2 processes available in the ready queue: P1 and P2.
    • Since the priority of process P2 is higher than the priority of process P1, therefore Process P2 will get executed first.
    • Hence Process P2 is executed for 1ms, from 1ms to 2ms. 
    • Remaining Burst time (B.T) for P2 = 4-1 = 3 ms.
Time InstanceProcessArrival TimePriorityExecution TimeInitial Burst TimeFinal Burst Time
1 ms – 2 ms P1   0 ms302 ms2 ms
 P2 1 ms214 ms3 ms
  • At time t = 2 ms, 
    • There are 3 processes available in the ready queue: P1, P2, and P3.
    • Since the priority of process P2 is higher than the priority of process P1 and P3, therefore Process P2 will get executed first.
    • Hence Process P2 is executed for 1ms, from 2ms to 3ms. 
    • Remaining Burst time (B.T) for P2 = 3-1 = 2 ms.
Time InstanceProcessArrival TimePriorityExecution TimeInitial Burst TimeFinal Burst Time
2 ms – 3 ms P1   0 ms302 ms2 ms
 P2 1 ms213 ms2 ms
 P3 2 ms4   06 ms6 ms
  • At time t = 3 ms, 
    • There are 4 processes available in the ready queue: P1, P2, P3, and P4.
    • Since the priority of process P2 is highest among the priority of processes P1, P2, P3, and P4, therefore Process P2 will get executed first.
    • Hence Process P2 is executed for 1ms, from 3ms to 4ms. 
    • Remaining Burst time (B.T) for P2 = 1-1 = 0 ms.
Time InstanceProcessArrival TimePriorityExecution TimeInitial Burst TimeFinal Burst Time
3 ms – 4 ms P1   0 ms302 ms2 ms
 P2 1 ms212 ms1 ms
 P3 2 ms4   06 ms6 ms
 P4 3 ms6   04 ms4 ms
  • At time t = 4 ms, 
    • There are 5 processes available in the ready queue: P1, P2, P3, P4, and P5.
    • Since the priority of process P2 is highest among the priority of processes P1, P2, P3, P4, and P5, therefore Process P2 will get executed first.
    • Hence Process P2 is executed for 1ms, from 4ms to 5ms. 
    • Remaining Burst time (B.T) for P2 = 1-1 = 0 ms.
    • Since Process P2’s burst time has become 0, therefore it is complete and will be removed from the process queue.
Time InstanceProcessArrival TimePriorityExecution TimeInitial Burst TimeFinal Burst Time
4 ms – 5 ms P1   0 ms302 ms2 ms
 P2 1 ms211 ms0 ms
 P3 2 ms4   06 ms6 ms
 P4 3 ms6   04 ms4 ms
 P5 5 ms10   02 ms2 ms
  • At time t = 5 ms, 
    • There are 4 processes available in the ready queue: P1, P3, P4, and P5.
    • Since the priority of process P1 is the highest among the priority of processes P1, P3, P4 and P5, therefore Process P1 will get executed first.
    • Hence Process P1 is executed for 2ms, from 5ms to 7ms. 
    • Remaining Burst time (B.T) for P1 = 2-2 = 0 ms.
    • Since Process P1’s burst time has become 0, therefore it is complete and will be removed from the process queue.
Time InstanceProcessArrival TimePriorityExecution TimeInitial Burst TimeFinal Burst Time
5 ms – 7 ms P1   0 ms322 ms0 ms
 P3 2 ms4   06 ms6 ms
 P4 3 ms6   04 ms4 ms
 P5 5 ms10   02 ms2 ms
  • At time t = 7 ms, 
    • There are 3 processes available in the ready queue: P3, P4, and P5.
    • Since the priority of process P3 is the highest among the priority of processes P3, P4, and P5, therefore Process P3 will get executed first.
    • Hence Process P3 is executed for 6ms, from 7ms to 13ms. 
    • Remaining Burst time (B.T) for P3 = 6-6 = 0 ms.
    • Since Process P3’s burst time has become 0, therefore it is complete and will be removed from the process queue.
Time InstanceProcessArrival TimePriorityExecution TimeInitial Burst TimeFinal Burst Time
7 ms – 13 ms P3 2 ms4   66 ms0 ms
 P4 3 ms6   04 ms4 ms
 P5 5 ms10   02 ms2 ms
  • At time t = 13 ms, 
    • There are 2 processes available in the ready queue: P4 and P5.
    • Since the priority of process P4 is highest among the priority of process P4 and P5, therefore Process P4 will get executed first.
    • Hence Process P4 is executed for 4ms, from 13ms to 17ms. 
    • Remaining Burst time (B.T) for P4 = 4-4 = 0 ms.
    • Since Process P4’s burst time has become 0, therefore it is complete and will be removed from the process queue.
Time InstanceProcessArrival TimePriorityExecution TimeInitial Burst TimeFinal Burst Time
13 ms – 17 ms P4 3 ms6   44 ms0 ms
 P5 5 ms10   02 ms2 ms
  • At time t = 17 ms, 
    • There is only 1 process available in the ready queue: P5.
    • Hence Process P5 is executed for 2ms, from 17ms to 19ms. 
    • Remaining Burst time (B.T) for P5 = 2-2 = 0 ms.
    • Since Process P5’s burst time has become 0, therefore it is complete and will be removed from the process queue.
Time InstanceProcessArrival TimePriorityExecution TimeInitial Burst TimeFinal Burst Time
17 ms – 19 ms P5 5 ms10   22 ms0 ms
  • At time t = 19 ms, 
    • There is no more process available in the ready queue. Hence the processing will now stop.
    • The overall execution of the processes will be as shown below:
Time InstanceProcessArrival TimePriorityExecution TimeInitial Burst TimeFinal Burst Time
0 ms – 1 ms P1   0 ms313 ms2 ms
1 ms – 2 ms P1   0 ms302 ms2 ms
 P2 1 ms214 ms3 ms
2 ms – 3 ms P1   0 ms302 ms2 ms
 P2 1 ms213 ms2 ms
 P3 2 ms4   06 ms6 ms
3 ms – 4 ms P1   0 ms302 ms2 ms
 P2 1 ms212 ms1 ms
 P3 2 ms4   06 ms6 ms
 P4 3 ms6   04 ms4 ms
4 ms – 5 ms P1   0 ms302 ms2 ms
 P2 1 ms211 ms0 ms
 P3 2 ms4   06 ms6 ms
 P4 3 ms6   04 ms4 ms
 P5 5 ms10   02 ms2 ms
5 ms – 7 ms P1   0 ms322 ms0 ms
 P3 2 ms4   06 ms6 ms
 P4 3 ms6   04 ms4 ms
 P5 5 ms10   02 ms2 ms
7 ms – 13 ms P3 2 ms4   66 ms0 ms
 P4 3 ms6   04 ms4 ms
 P5 5 ms10   02 ms2 ms
13 ms – 17 ms P4 3 ms6   44 ms0 ms
 P5 5 ms10   02 ms2 ms
17 ms – 19 ms P5 5 ms10   22 ms0 ms

Gantt chart for above execution:

Now we need to calculate the completion time (C.T) & First Arrival Time (F.A.T) of each process through Gantt chart, as per the below relations:

Turn Around Time (T.A.T) = (Completion Time) – (Arrival Time)

Waiting Time (W.T) = (Turn Around Time) – (Burst Time)

Response Time (R.T) = (First Arrival Time) – (Arrival Time)

After calculating the above fields, the final table looks like

The final table

The final table

Here, H – Highest Priority, and L – Least Priority

Some other important relations for this example include:

  • Total Turn Around Time = 7 + 4 + 11 + 14 + 14 = 50 ms
  • Average Turn Around Time = (Total Turn Around Time)/(no. of processes) = 50/5 = 10.00 ms
  • Total Waiting Time = 4 + 0 + 5 + 10 + 12 = 31 ms
  • Average Waiting Time = (Total Waiting Time)/(no. of processes) = 31/5 = 6.20 ms
  • Total Response Time = 0 + 0 + 5 + 10 + 12 = 27 ms
  • Average Response Time = (Total Response Time)/(no. of processes) = 27/5 = 5.40 ms

Example 2: 

Consider the following table of arrival time, Priority and burst time for seven processes P1, P2, P3, P4, P5, P6 and P7

ProcessArrival TimePriority  Burst Time
P1      0 ms3 8 ms
P2   1 ms4 2 ms
P3  3 ms4       4 ms
P4  4 ms5 1 ms
P5  5 ms2 6 ms
P6  6 ms6     5 ms
P7       10 ms1 1 ms
  • At time t = 0, 
    • Process P1 is available in the ready queue, executing P1 for 1 ms
    • Remaining B.T for P1 = 8-1 = 7 ms.
       
  • At time t = 1, 
    • The priority of P1 is greater than P2, so we execute P1 for 2 ms, from 1 ms to 3 ms.
    • Remaining B.T for P1 = 7-2 = 5 ms.
  • At time t = 3, 
    • The priority of P1 is greater than P3, so we execute P1 for 1 ms.
    • Remaining B.T for P1 = 5-1 = 4 ms.
  • At time t = 4, 
    • The priority of P1 is greater than P4, so we execute P1 for 1 ms.
    • Remaining B.T for P1 = 4-1 = 3 ms.
  • At time t = 5, 
    • The priority of P5 is greater than P1, so we execute P5 for 1 ms.
    • Remaining B.T for P5 = 6-1 = 5 ms.
  • At time t = 6, 
    • The priority of P5 is greater than P6, so we execute P5 for 4 ms.
    • Remaining B.T for P5 = 5-4 = 1 ms.
  • At time t = 10, 
    • The priority of P7 is greater than P5, so we execute P7 for 1 ms.
    • Remaining B.T for P7 = 1-1 = 0 ms.
    • Here Process P7 completes its execution.
  • At time t = 11,
    • Now we take the process which is having the highest priority. 
    • Here we find P5 is having the highest priority & execute P5 completely 
    • Remaining B.T of P5 = 1-1 = 0 ms.
    • Here Process P5 completes its execution.
  • At time t = 12,
    • Now we take the process which is having the highest priority. 
    • Here we find P1 is having the highest priority & execute P1 completely 
    • Remaining B.T of P1 = 3-3 = 0 ms.
    • Here Process P1 completes its execution.
  • At time t = 15,
    • Now we take the process which is having the highest priority. 
    • Here we find P2 is having the highest priority & execute P2 completely 
    • Remaining B.T of P2 = 2-2 = 0 ms.
    • Here Process P2 completes its execution.
  • At time t = 17,
    • Now we take the process which is having the highest priority. 
    • Here we find P3 is having the highest priority & execute P3 completely 
    • Remaining B.T of P3 = 4-4 = 0 ms.
    • Here Process P3 completes its execution.
  • At time t = 21,
    • Now we take the process which is having the highest priority. 
    • Here we find P4 is having the highest priority & execute P4 completely 
    • Remaining B.T of P4 = 1-1 = 0 ms.
    • Here Process P4 completes its execution.
  • At time t = 22,
    • Now we take the process which is having the highest priority. 
    • Here we find P6 is having the highest priority & execute P6 completely 
    • Remaining B.T of P6 = 5-5 = 0 ms.
    • Here Process P6 completes its execution.

Gantt chart:

Here, H – Higher Priority, L – Least Priority

C++
#include <iostream>
#include <vector>
#include <algorithm>

struct Process {
    int processID;
    int burstTime;
    int tempburstTime;
    int responsetime;
    int arrivalTime;
    int priority;
    int outtime;
    int intime;
};

void insert(Process Heap[], Process value, int* heapsize, int* currentTime) {
    int start = *heapsize;
    Heap[*heapsize] = value;
    if (Heap[*heapsize].intime == -1)
        Heap[*heapsize].intime = *currentTime;
    ++(*heapsize);

    while (start != 0 && Heap[(start - 1) / 2].priority > Heap[start].priority) {
        Process temp = Heap[(start - 1) / 2];
        Heap[(start - 1) / 2] = Heap[start];
        Heap[start] = temp;
        start = (start - 1) / 2;
    }
}

void order(Process Heap[], int* heapsize, int start) {
    int smallest = start;
    int left = 2 * start + 1;
    int right = 2 * start + 2;
    if (left < *heapsize && Heap[left].priority < Heap[smallest].priority)
        smallest = left;
    if (right < *heapsize && Heap[right].priority < Heap[smallest].priority)
        smallest = right;

    if (smallest != start) {
        Process temp = Heap[smallest];
        Heap[smallest] = Heap[start];
        Heap[start] = temp;
        order(Heap, heapsize, smallest);
    }
}

Process extractminimum(Process Heap[], int* heapsize, int* currentTime) {
    Process min = Heap[0];
    if (min.responsetime == -1)
        min.responsetime = *currentTime - min.arrivalTime;
    --(*heapsize);
    if (*heapsize >= 1) {
        Heap[0] = Heap[*heapsize];
        order(Heap, heapsize, 0);
    }
    return min;
}

bool compare(Process p1, Process p2) {
    return (p1.arrivalTime < p2.arrivalTime);
}

void scheduling(Process Heap[], Process array[], int n, int* heapsize, int* currentTime) {
    if (*heapsize == 0)
        return;

    Process min = extractminimum(Heap, heapsize, currentTime);
    min.outtime = *currentTime + 1;
    --min.burstTime;
    std::cout << "process id = " << min.processID << " current time = " << *currentTime << std::endl;

    if (min.burstTime > 0) {
        insert(Heap, min, heapsize, currentTime);
        return;
    }

    for (int i = 0; i < n; i++)
        if (array[i].processID == min.processID) {
            array[i] = min;
            break;
        }
}

void priority(Process array[], int n) {
    std::sort(array, array + n, compare);

    int totalwaitingtime = 0, totalbursttime = 0, totalturnaroundtime = 0, i, insertedprocess = 0, heapsize = 0,
        currentTime = array[0].arrivalTime, totalresponsetime = 0;

    Process Heap[4 * n];

    for (int i = 0; i < n; i++) {
        totalbursttime += array[i].burstTime;
        array[i].tempburstTime = array[i].burstTime;
    }

    do {
        if (insertedprocess != n) {
            for (i = 0; i < n; i++) {
                if (array[i].arrivalTime == currentTime) {
                    ++insertedprocess;
                    array[i].intime = -1;
                    array[i].responsetime = -1;
                    insert(Heap, array[i], &heapsize, &currentTime);
                }
            }
        }
        scheduling(Heap, array, n, &heapsize, &currentTime);
        ++currentTime;
        if (heapsize == 0 && insertedprocess == n)
            break;
    } while (1);

    for (int i = 0; i < n; i++) {
        totalresponsetime += array[i].responsetime;
        totalwaitingtime += (array[i].outtime - array[i].intime - array[i].tempburstTime);
        totalbursttime += array[i].burstTime;
    }

    std::cout << "Average waiting time = " << ((float)totalwaitingtime / (float)n) << std::endl;
    std::cout << "Average response time = " << ((float)totalresponsetime / (float)n) << std::endl;
    std::cout << "Average turn around time = " << ((float)(totalwaitingtime + totalbursttime) / (float)n) << std::endl;
}

int main() {
    int n, i;
    Process a[5];
    a[0].processID = 1;
    a[0].arrivalTime = 4;
    a[0].priority = 2;
    a[0].burstTime = 6;
    a[1].processID = 4;
    a[1].arrivalTime = 5;
    a[1].priority = 1;
    a[1].burstTime = 3;
    a[2].processID = 2;
    a[2].arrivalTime = 5;
    a[2].priority = 3;
    a[2].burstTime = 1;
    a[3].processID = 3;
    a[3].arrivalTime = 1;
    a[3].priority = 4;
    a[3].burstTime = 2;
    a[4].processID = 5;
    a[4].arrivalTime = 3;
    a[4].priority = 5;
    a[4].burstTime = 4;
    priority(a, 5);
    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <stdbool.h>

void srtn(int pid[], int at[], int bt[], int wt[], int tat[], int size)
{
    printf("\n-------------------------------------------------------------------------------");
    printf("\nInside SRTN function...");
    printf("\n-------------------------------------------------------------------------------");
    printf("\nPrinting data...");
    printf("\nProcess ID\tArrival Time\tBurst Time\tWaiting Time\tTurnaround Time");
    for(int i = 0; i < size; i++){
        printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d", pid[i], at[i], bt[i], wt[i], tat[i]);
    }
    printf("\n-------------------------------------------------------------------------------");
    printf("\nForming table...");
    int remaining_time[size];
    bool completed[size];
    for (int i = 0; i < size; i++) {
        remaining_time[i] = bt[i];
        completed[i] = false;
    }
    int current_time = 0;
    int completed_processes = 0;
    printf("\nJob\tArrival Time\tBurst Time\tFinish Time\tTurnaround Time\tWaiting Time\n");
    while (completed_processes < size) {
        int shortest_job = -1;
        int shortest_time = 9999; // A large number as initial value
        for (int i = 0; i < size; i++) {
            if (at[i] <= current_time && !completed[i] && remaining_time[i] < shortest_time) {
                shortest_job = i;
                shortest_time = remaining_time[i];
            }
        }
        if (shortest_job == -1) {
            current_time++;
        } else {
            remaining_time[shortest_job]--;
            if (remaining_time[shortest_job] == 0) {
                completed_processes++;
                int finish_time = current_time + 1;
                tat[shortest_job] = finish_time - at[shortest_job];
                wt[shortest_job] = tat[shortest_job] - bt[shortest_job];
                completed[shortest_job] = true;

                printf("%c\t%d\t\t%d\t\t%d\t\t%d\t\t%d\n", 'A' + pid[shortest_job], at[shortest_job], bt[shortest_job], finish_time, tat[shortest_job], wt[shortest_job]);
            }
            current_time++;
        }
    }
    printf("\n-------------------------------------------------------------------------------");
    printf("\n-------------------------------------------------------------------------------");
    printf("\n-------------------------------------------------------------------------------");   
}

void rr(int pid[], int at[], int bt[], int size, int quantum)
{
    //pid is analogous to Array1; bt is analogous to Array2; wt is analogous to Array3
    printf("\n-------------------------------------------------------------------------------");
    printf("\nInside RR function...");
    printf("\n-------------------------------------------------------------------------------");
    printf("\nPrinting data...");
    printf("\nProcess ID\tArrival Time\tBurst Time");
    for(int i = 0; i < size; i++){
        printf("\n%d\t\t%d\t\t%d", pid[i], at[i], bt[i]);
    }
    printf("\n-------------------------------------------------------------------------------\n");
    int remaining_time[size];
    int finish_time[size];
    int tat[size];
    int wt[size];
    int time = 0;
    int total_tat = 0;
    int total_wt = 0;
    for (int i = 0; i < size; i++) {
        remaining_time[i] = bt[i];
        finish_time[i] = 0;
        tat[i] = 0;
        wt[i] = 0;
    }
    int done = 0;
    while (!done) {
        done = 1;
        for (int i = 0; i < size; i++) {
            if (remaining_time[i] > 0) {
                done = 0;

                if (remaining_time[i] > quantum) {
                    time += quantum;
                    remaining_time[i] -= quantum;
                } else {
                    time += remaining_time[i];
                    finish_time[i] = time;
                    tat[i] = finish_time[i] - at[i];
                    wt[i] = tat[i] - bt[i];
                    total_tat += tat[i];
                    total_wt += wt[i];
                    remaining_time[i] = 0;
                }
            }
        }
    }
    // Print the table
    printf("Job\tArrival Time\tBurst Time\tFinish Time\tTurnaround Time\tWaiting Time\n");
    for (int i = 0; i < size; i++) {
        printf("%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d\n", pid[i], at[i], bt[i], finish_time[i], tat[i], wt[i]);
    }
    // Calculate and print average turnaround time and waiting time
    float avg_tat = (float)total_tat / size;
    float avg_wt = (float)total_wt / size;
    printf("Average\t%.1f\t%.1f\n", avg_tat, avg_wt);
    printf("\n-------------------------------------------------------------------------------");
    printf("\n-------------------------------------------------------------------------------");
    printf("\n-------------------------------------------------------------------------------");
}

void priority(int pid[], int at[], int bt[], int wt[], int tat[], int p[], int size)
{
    printf("\n-------------------------------------------------------------------------------");
    printf("\nInside Priority function...");
    printf("\n-------------------------------------------------------------------------------");
    printf("\nPrinting data...");
    printf("\nProcess ID\tArrival Time\tBurst Time\tWaiting Time\tTurnaround Time");
    for(int i = 0; i < size; i++){
        printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d", pid[i], at[i], bt[i], wt[i], tat[i]);
    }
    printf("\n-------------------------------------------------------------------------------\n");\
    int remaining_time[size];
    int current_time = 0;
    int completed = 0;
    // Initialize the remaining time for each process
    for (int i = 0; i < size; i++) {
        remaining_time[i] = bt[i];
    }
    printf("Process\tArrival Time\tBurst Time\tPriority\tFinish Time\tTurnaround Time\tWaiting Time\n");
    while (completed < size) {
        int selected = -1;
        int highest_priority = 9999; // A large initial value
        for (int i = 0; i < size; i++) {
            if (at[i] <= current_time && remaining_time[i] > 0 && p[i] < highest_priority) {
                selected = i;
                highest_priority = p[i];
            }
        }
        if (selected == -1) {
            current_time++;
        } else {
            remaining_time[selected]--;
            current_time++;
            if (remaining_time[selected] == 0) {
                completed++;
                int finish_time = current_time;
                int turnaround_time = finish_time - at[selected];
                int waiting_time = turnaround_time - bt[selected];
                printf("P%d\t%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d\n", pid[selected], at[selected], bt[selected], p[selected], finish_time, turnaround_time, waiting_time);
                wt[selected] = waiting_time;
                tat[selected] = turnaround_time;
            }
        }
    }
    printf("\n-------------------------------------------------------------------------------");
    printf("\n-------------------------------------------------------------------------------");
    printf("\n-------------------------------------------------------------------------------");
}

int main() 
{
    printf("\n-------------------------------------------------------------------------------");
    printf("\n--------------------Preemptive Scheduling Algorithm Program--------------------");
    printf("\n-------------------------------------------------------------------------------");
    int ch_run;
    while(0 < 1){
        fflush(stdin);
        printf("\nEnter 1 for Shortest Remaining Time Next\nEnter 2 for Round Robin\nEnter 3 for Priority\nEnter choice: ");
        int ch_algo, n;
        scanf("%d", &ch_algo);
        printf("\n-----------------------------------------------------------------------------------");
        printf("\nEnter 1 for default values and 2 for custom values\nEnter choice: ");
        int ch_val;
        scanf("%d", &ch_val);
        if(ch_val == 1){
            n = 5;
            int pid[n], wt[n], tat[n];
            printf("\n-----------------------------------------------------------------------------------");
            printf("\nEntered data: Choice = %d, Number of processes = %d", ch_algo, n);
            printf("\n-----------------------------------------------------------------------------------");
            //Initializing Process ID Array
            for(int i = 0; i < n; i++){
                pid[i] = i;
                printf("\nProcess %d has got Process ID %d.", i+1, pid[i]);
            }
            printf("\nProcess ID Array initialized successfully.");
            printf("\n-----------------------------------------------------------------------------------");
            int at[] = {2, 0, 1, 4, 3};
            for(int i = 0; i < n; i++)
                printf("\nProcess %d has got Arrival Time %d.", i+1, at[i]);
            printf("\n-----------------------------------------------------------------------------------");
            int bt[] = {6, 4, 8, 3, 2};
            for(int i = 0; i < n; i++)
                printf("\nProcess %d has got Burst Time %d.", i+1, bt[i]);
            int quantum;
            switch(ch_algo)
            {
                case 1:
                    printf("\nYou selected SRTN!");
                    srtn(pid, at, bt, wt, tat, n);
                    break;
                case 2:
                    printf("\nYou selected RR!");
                    printf("\nEnter time quantum: ");
                    scanf("%d", &quantum);
                    rr(pid, at, bt, n, quantum);
                    break;
                case 3:
                    printf("\nYou selected Priority!");
                    printf("\n-----------------------------------------------------------------------------------");
                    int p[] = {0, 2, 4, 1, 3};
                    for(int i = 0; i < n; i++)
                        printf("\nProcess %d has got Priority %d.", i+1, p[i]);
                    priority(pid, at, bt, wt, tat, p, n);
                    break;
                default:
                    printf("\nInvalid choice!");
            }
        } else {
            printf("\n-----------------------------------------------------------------------------------");
            printf("\nEnter the number of processes in ready queue (arrival time of all processes is assumed to be 0 ms): ");
            scanf("%d", &n);
            printf("\n-----------------------------------------------------------------------------------");
            printf("\nEntered data: Choice = %d, Number of processes = %d", ch_algo, n);
            printf("\n-----------------------------------------------------------------------------------");
            int pid[n], at[n], bt[n], wt[n], tat[n], p[n];
            //Initializing Process ID Array
            for(int i = 0; i < n; i++){
                pid[i] = i;
                printf("\nProcess %d has got Process ID %d.", i+1, pid[i]);
            }
            printf("\nProcess ID Array initialized successfully.");
            printf("\n-----------------------------------------------------------------------------------");
            printf("\nEnter arrival time for each process.");
            //Array to store the arrival times of all processes
            for(int i = 0; i < n; i++){
                printf("\nArrival time for Process ID %d: ", pid[i]);
                scanf("%d", &at[i]);
            }
            printf("\n-----------------------------------------------------------------------------------");
            printf("\nEnter burst time (execution time) for each process.");
            //Array to store the burst times of all processes
            for(int i = 0; i < n; i++){
                printf("\nBurst time for Process ID %d: ", pid[i]);
                scanf("%d", &bt[i]);
            }
            printf("\n-----------------------------------------------------------------------------------");
            //Array to store the waiting times of all processes
            //n is the process id.
            //If wt[1] = 5, then it implies that the process with process id 1 has a waiting time of 5 ms.
            wt[0] = 0;
            //The process with process id 0 has a wait time of 0 ms, in a system where all processes arrive at 0 ms.
            //Array to store the turnaround time of all processes
            int quantum;
            switch(ch_algo)
            {
                case 1:
                    printf("\nYou selected SRTN!");
                    srtn(pid, at, bt, wt, tat, n);
                    break;
                case 2:
                    printf("\nYou selected RR!");
                    printf("\nEnter time quantum: ");
                    scanf("%d", &quantum);
                    rr(pid, at, bt, n, quantum);
                    break;
                case 3:
                    printf("\nYou selected Priority!");
                    printf("\n-----------------------------------------------------------------------------------");
                    printf("\nEnter burst time (execution time) for each process.");
                    //Array to store the burst times of all processes
                    for(int i = 0; i < n; i++){
                        printf("\nBurst time for Process ID %d: ", pid[i]);
                        scanf("%d", &p[i]);
                    }
                    for(int i = 0; i < n; i++)
                        printf("\nProcess %d has got Priority %d.", i+1, p[i]);
                    priority(pid, at, bt, wt, tat, p, n);
                    break;
                default:
                    printf("\nInvalid choice!");
            }
        }
        printf("\nDo you want to run the program again? Enter '1' else any integer.\nEnter your choice: ");
        scanf("%d", &ch_run);
        if(ch_run == 1){
            continue;
        } else {
            break;
        }
    }
    return 0;
}
Java
import java.util.Arrays;
import java.util.Comparator;

// Definition of Process class
class Process {
    int processID;
    int arrivalTime;
    int priority;
    int burstTime;
    int tempburstTime;
    int responsetime = -1;
    int outtime;
    int intime = -1;

    // Constructor
    public Process(int processID, int arrivalTime, int priority, int burstTime) {
        this.processID = processID;
        this.arrivalTime = arrivalTime;
        this.priority = priority;
        this.burstTime = burstTime;
        this.tempburstTime = burstTime;
    }
}

// Main class
public class PriorityScheduling {

    // Function to insert a process into the heap
    static void insert(Process[] Heap, Process value, int[] heapsize, int[] currentTime) {
        int start = heapsize[0];
        Heap[start] = value;
        if (Heap[start].intime == -1)
            Heap[start].intime = currentTime[0];
        heapsize[0]++;

        // Ordering the Heap
        while (start != 0 && Heap[(start - 1) / 2].priority > Heap[start].priority) {
            Process temp = Heap[(start - 1) / 2];
            Heap[(start - 1) / 2] = Heap[start];
            Heap[start] = temp;
            start = (start - 1) / 2;
        }
    }

    // Function to reorder the heap based on priority
    static void order(Process[] Heap, int[] heapsize, int start) {
        int smallest = start;
        int left = 2 * start + 1;
        int right = 2 * start + 2;
        if (left < heapsize[0] && Heap[left].priority < Heap[smallest].priority)
            smallest = left;
        if (right < heapsize[0] && Heap[right].priority < Heap[smallest].priority)
            smallest = right;

        // Ordering the Heap
        if (smallest != start) {
            Process temp = Heap[smallest];
            Heap[smallest] = Heap[start];
            Heap[start] = temp;
            order(Heap, heapsize, smallest);
        }
    }

    // Function to extract the process with the highest priority from the heap
    static Process extractminimum(Process[] Heap, int[] heapsize, int[] currentTime) {
        Process min_process = Heap[0];
        if (min_process.responsetime == -1)
            min_process.responsetime = currentTime[0] - min_process.arrivalTime;
        heapsize[0]--;
        if (heapsize[0] >= 1) {
            Heap[0] = Heap[heapsize[0]];
            order(Heap, heapsize, 0);
        }
        return min_process;
    }

    // Function to compare two processes based on arrival time
    static boolean compare(Process p1, Process p2) {
        return p1.arrivalTime < p2.arrivalTime;
    }

    // Function responsible for executing the highest priority process extracted from the heap
    static void scheduling(Process[] Heap, Process[] array, int n, int[] heapsize, int[] currentTime) {
        if (heapsize[0] == 0)
            return;

        Process min_process = extractminimum(Heap, heapsize, currentTime);
        min_process.outtime = currentTime[0] + 1;
        min_process.burstTime--;
        System.out.println("process id = " + min_process.processID + " current time = " + currentTime[0]);

        // If the process is not yet finished, insert it back into the Heap
        if (min_process.burstTime > 0) {
            insert(Heap, min_process, heapsize, currentTime);
            return;
        }

        for (int i = 0; i < n; i++)
            if (array[i].processID == min_process.processID) {
                array[i] = min_process;
                break;
            }
    }

    // Function responsible for managing the entire execution of processes based on arrival time
    static void priority(Process[] array, int n) {
        Arrays.sort(array, Comparator.comparingInt(a -> a.arrivalTime));

        int total_waiting_time = 0;
        int total_burst_time = 0;
        int total_turnaround_time = 0;
        int inserted_process = 0;
        int[] heap_size = {0};
        int current_time = array[0].arrivalTime;
        int total_response_time = 0;

        Process[] Heap = new Process[4 * n];

        // Calculating the total burst time of the processes
        for (int i = 0; i < n; i++) {
            total_burst_time += array[i].burstTime;
            array[i].tempburstTime = array[i].burstTime;
        }

        // Inserting the processes into Heap according to arrival time
        while (true) {
            if (inserted_process != n) {
                for (int i = 0; i < n; i++) {
                    if (array[i].arrivalTime == current_time) {
                        inserted_process++;
                        array[i].intime = -1;
                        array[i].responsetime = -1;
                        insert(Heap, array[i], heap_size, new int[]{current_time});
                    }
                }
            }
            scheduling(Heap, array, n, heap_size, new int[]{current_time});
            current_time++;
            if (heap_size[0] == 0 && inserted_process == n)
                break;
        }

        for (int i = 0; i < n; i++) {
            total_response_time += array[i].responsetime;
            total_waiting_time += (array[i].outtime - array[i].intime - array[i].tempburstTime);
            total_turnaround_time += (array[i].outtime - array[i].intime);
            total_burst_time += array[i].burstTime;
        }

        System.out.println("Average waiting time = " + ((float) total_waiting_time / n));
        System.out.println("Average response time = " + ((float) total_response_time / n));
        System.out.println("Average turn around time = " + ((float) total_turnaround_time / n));
    }

    // Driver code
    public static void main(String[] args) {
        int n = 5;
        Process[] a = {
                new Process(1, 4, 2, 6),
                new Process(4, 5, 1, 3),
                new Process(2, 5, 3, 1),
                new Process(3, 1, 4, 2),
                new Process(5, 3, 5, 4)
        };
        priority(a, n);
    }
}
//This code is contributed by Monu.
C#
using System;
using System.Collections.Generic;
using System.Linq;

class Process
{
    public int ProcessID { get; set; }
    public int ArrivalTime { get; set; }
    public int Priority { get; set; }
    public int BurstTime { get; set; }
    public int TempBurstTime { get; set; }
    public int ResponseTime { get; set; } = -1;
    public int OutTime { get; set; }
    public int InTime { get; set; } = -1;

    // Constructor to initialize a Process object
    public Process(int processID, int arrivalTime, int priority, int burstTime)
    {
        ProcessID = processID;
        ArrivalTime = arrivalTime;
        Priority = priority;
        BurstTime = burstTime;
        TempBurstTime = burstTime;
    }
}

class Program
{
    // Function to insert a process into the heap
    static void Insert(List<Process> heap, Process value, 
                       ref int heapSize, ref int currentTime)
    {
        int start = heapSize;
        heap.Add(value);
        if (heap[heapSize].InTime == -1)
            heap[heapSize].InTime = currentTime;
        heapSize++;

        // Ordering the Heap
        while (start != 0 && heap[(start - 1) / 2].Priority > heap[start].Priority)
        {
            Process temp = heap[(start - 1) / 2];
            heap[(start - 1) / 2] = heap[start];
            heap[start] = temp;
            start = (start - 1) / 2;
        }
    }

    // Function to reorder the heap based on priority
    static void Order(List<Process> heap, int heapSize, int start)
    {
        int smallest = start;
        int left = 2 * start + 1;
        int right = 2 * start + 2;
        if (left < heapSize && heap[left].Priority < heap[smallest].Priority)
            smallest = left;
        if (right < heapSize && heap[right].Priority < heap[smallest].Priority)
            smallest = right;

        // Ordering the Heap
        if (smallest != start)
        {
            Process temp = heap[smallest];
            heap[smallest] = heap[start];
            heap[start] = temp;
            Order(heap, heapSize, smallest);
        }
    }

    // Function to extract the process with the highest priority from the heap
    static Process ExtractMinimum(List<Process> heap, ref int heapSize, ref int currentTime)
    {
        Process minProcess = heap[0];
        if (minProcess.ResponseTime == -1)
            minProcess.ResponseTime = currentTime - minProcess.ArrivalTime;
        heapSize--;
        if (heapSize >= 1)
        {
            heap[0] = heap[heapSize];
            Order(heap, heapSize, 0);
        }
        return minProcess;
    }

    // Function to compare two processes based on arrival time
    static bool Compare(Process p1, Process p2)
    {
        return p1.ArrivalTime < p2.ArrivalTime;
    }

    // Function responsible for executing the highest priority process extracted from the heap
    static void Scheduling(List<Process> heap, List<Process> array, 
                           int n, ref int heapSize, ref int currentTime)
    {
        if (heapSize == 0)
            return;

        Process minProcess = ExtractMinimum(heap, ref heapSize, ref currentTime);
        minProcess.OutTime = currentTime + 1;
        minProcess.BurstTime--;

        Console.WriteLine($"process id = {minProcess.ProcessID} current time = {currentTime}");

        // If the process is not yet finished, insert it back into the Heap
        if (minProcess.BurstTime > 0)
        {
            Insert(heap, minProcess, ref heapSize, ref currentTime);
            return;
        }

        for (int i = 0; i < n; i++)
        {
            if (array[i].ProcessID == minProcess.ProcessID)
            {
                array[i] = minProcess;
                break;
            }
        }
    }

    // Function responsible for managing the entire execution of 
    // processes based on arrival time
    static void Priority(List<Process> array, int n)
    {
        array = array.OrderBy(p => p.ArrivalTime).ToList();

        int totalWaitingTime = 0;
        int totalBurstTime = 0;
        int totalTurnaroundTime = 0;
        int insertedProcess = 0;
        int heapSize = 0;
        int currentTime = array[0].ArrivalTime;
        int totalResponseTime = 0;

        List<Process> heap = new List<Process>(4 * n);

        // Calculating the total burst time of the processes
        for (int i = 0; i < n; i++)
        {
            totalBurstTime += array[i].BurstTime;
            array[i].TempBurstTime = array[i].BurstTime;
        }

        // Inserting the processes in Heap according to arrival time
        do
        {
            if (insertedProcess != n)
            {
                for (int i = 0; i < n; i++)
                {
                    if (array[i].ArrivalTime == currentTime)
                    {
                        insertedProcess++;
                        array[i].InTime = -1;
                        array[i].ResponseTime = -1;
                        Insert(heap, array[i], ref heapSize, ref currentTime);
                    }
                }
            }
            Scheduling(heap, array, n, ref heapSize, ref currentTime);
            currentTime++;
            if (heapSize == 0 && insertedProcess == n)
                break;
        } while (true);

        for (int i = 0; i < n; i++)
        {
            totalResponseTime += array[i].ResponseTime;
            totalWaitingTime += (array[i].OutTime - array[i].InTime - array[i].TempBurstTime);
            totalTurnaroundTime += (array[i].OutTime - array[i].InTime);
            totalBurstTime += array[i].BurstTime;
        }

        Console.WriteLine($"Average waiting time = {totalWaitingTime / (float)n}");
        Console.WriteLine($"Average response time = {totalResponseTime / (float)n}");
        Console.WriteLine($"Average turn around time = {totalTurnaroundTime / (float)n}");
    }

    static void Main(string[] args)
    {
        int n = 5;
        List<Process> a = new List<Process>
        {
            new Process(1, 4, 2, 6),
            new Process(4, 5, 1, 3),
            new Process(2, 5, 3, 1),
            new Process(3, 1, 4, 2),
            new Process(5, 3, 5, 4)
        };

        Priority(a, n);
    }
}
JavaScript
class Process {
    constructor(processID, arrivalTime, priority, burstTime) {
        this.processID = processID;
        this.arrivalTime = arrivalTime;
        this.priority = priority;
        this.burstTime = burstTime;
        this.tempburstTime = burstTime;
        this.responsetime = -1;
        this.outtime = 0;
        this.intime = -1;
    }
}

function insert(Heap, value, heapsize, currentTime) {
    let start = heapsize[0];
    Heap[start] = value;
    if (Heap[start].intime === -1) {
        Heap[start].intime = currentTime;
    }
    heapsize[0]++;

    while (start !== 0 && Heap[Math.floor((start - 1) / 2)].priority > Heap[start].priority) {
        [Heap[Math.floor((start - 1) / 2)], Heap[start]] = [Heap[start], Heap[Math.floor((start - 1) / 2)]];
        start = Math.floor((start - 1) / 2);
    }
}

function order(Heap, heapsize, start) {
    let smallest = start;
    let left = 2 * start + 1;
    let right = 2 * start + 2;
    if (left < heapsize[0] && Heap[left].priority < Heap[smallest].priority) {
        smallest = left;
    }
    if (right < heapsize[0] && Heap[right].priority < Heap[smallest].priority) {
        smallest = right;
    }

    if (smallest !== start) {
        [Heap[start], Heap[smallest]] = [Heap[smallest], Heap[start]];
        order(Heap, heapsize, smallest);
    }
}

function extractminimum(Heap, heapsize, currentTime) {
    let min_process = Heap[0];
    if (min_process.responsetime === -1) {
        min_process.responsetime = currentTime - min_process.arrivalTime;
    }
    heapsize[0]--;
    if (heapsize[0] >= 1) {
        Heap[0] = Heap[heapsize[0]];
        order(Heap, heapsize, 0);
    }
    return min_process;
}

function scheduling(Heap, array, n, heapsize, currentTime) {
    if (heapsize[0] === 0) {
        return;
    }

    let min_process = extractminimum(Heap, heapsize, currentTime);
    min_process.outtime = currentTime + 1;
    min_process.burstTime--;

    console.log(`process id = ${min_process.processID} current time = ${currentTime}`);

    if (min_process.burstTime > 0) {
        insert(Heap, min_process, heapsize, currentTime);
        return;
    }

    for (let i = 0; i < n; i++) {
        if (array[i].processID === min_process.processID) {
            array[i] = min_process;
            break;
        }
    }
}

function priority(array, n) {
    array.sort((a, b) => a.arrivalTime - b.arrivalTime);

    let total_waiting_time = 0;
    let total_burst_time = 0;
    let total_turnaround_time = 0;
    let inserted_process = 0;
    let heap_size = [0];
    let current_time = array[0].arrivalTime;
    let total_response_time = 0;

    let Heap = new Array(4 * n);

    for (let i = 0; i < n; i++) {
        total_burst_time += array[i].burstTime;
        array[i].tempburstTime = array[i].burstTime;
    }

    while (true) {
        if (inserted_process !== n) {
            for (let i = 0; i < n; i++) {
                if (array[i].arrivalTime === current_time) {
                    inserted_process++;
                    array[i].intime = -1;
                    array[i].responsetime = -1;
                    insert(Heap, array[i], heap_size, current_time);
                }
            }
        }
        scheduling(Heap, array, n, heap_size, current_time);
        current_time++;

        if (heap_size[0] === 0 && inserted_process === n) {
            break;
        }
    }

    for (let i = 0; i < n; i++) {
        total_response_time += array[i].responsetime;
        total_waiting_time += (array[i].outtime - array[i].intime - array[i].tempburstTime);
        total_turnaround_time += (array[i].outtime - array[i].intime);
        total_burst_time += array[i].burstTime;
    }

    console.log(`Average waiting time = ${total_waiting_time / n}`);
    console.log(`Average response time = ${total_response_time / n}`);
    console.log(`Average turn around time = ${total_turnaround_time / n}`);
}

const n = 5;
const a = [
    new Process(1, 4, 2, 6),
    new Process(4, 5, 1, 3),
    new Process(2, 5, 3, 1),
    new Process(3, 1, 4, 2),
    new Process(5, 3, 5, 4)
];

priority(a, n);
//This code is contributed by Monu.
Python3
import functools

class Process:
    def __init__(self, processID, arrivalTime, priority, burstTime):
        self.processID = processID
        self.arrivalTime = arrivalTime
        self.priority = priority
        self.burstTime = burstTime
        self.tempburstTime = burstTime
        self.responsetime = -1
        self.outtime = 0
        self.intime = -1

# Function to insert a process into the heap
def insert(Heap, value, heapsize, currentTime):
    start = heapsize[0]
    Heap[start] = value
    if Heap[start].intime == -1:
        Heap[start].intime = currentTime
    heapsize[0] += 1

    # Ordering the Heap
    while start != 0 and Heap[(start - 1) // 2].priority > Heap[start].priority:
        Heap[(start - 1) // 2], Heap[start] = Heap[start], Heap[(start - 1) // 2]
        start = (start - 1) // 2

# Function to reorder the heap based on priority
def order(Heap, heapsize, start):
    smallest = start
    left = 2 * start + 1
    right = 2 * start + 2
    if left < heapsize[0] and Heap[left].priority < Heap[smallest].priority:
        smallest = left
    if right < heapsize[0] and Heap[right].priority < Heap[smallest].priority:
        smallest = right

    # Ordering the Heap
    if smallest != start:
        Heap[start], Heap[smallest] = Heap[smallest], Heap[start]
        order(Heap, heapsize, smallest)

# Function to extract the process with the highest priority from the heap
def extractminimum(Heap, heapsize, currentTime):
    min_process = Heap[0]
    if min_process.responsetime == -1:
        min_process.responsetime = currentTime - min_process.arrivalTime
    heapsize[0] -= 1
    if heapsize[0] >= 1:
        Heap[0] = Heap[heapsize[0]]
        order(Heap, heapsize, 0)
    return min_process

# Function to compare two processes based on arrival time
def compare(p1, p2):
    return p1.arrivalTime < p2.arrivalTime

# Function responsible for executing the highest priority process extracted from the heap
def scheduling(Heap, array, n, heapsize, currentTime):
    if heapsize[0] == 0:
        return

    min_process = extractminimum(Heap, heapsize, currentTime)
    min_process.outtime = currentTime + 1
    min_process.burstTime -= 1
    print(f"process id = {min_process.processID} current time = {currentTime}")

    # If the process is not yet finished, insert it back into the Heap
    if min_process.burstTime > 0:
        insert(Heap, min_process, heapsize, currentTime)
        return

    for i in range(n):
        if array[i].processID == min_process.processID:
            array[i] = min_process
            break

# Function responsible for managing the entire execution of processes based on arrival time
def priority(array, n):
    array.sort(key=lambda x: x.arrivalTime)

    total_waiting_time = 0
    total_burst_time = 0
    total_turnaround_time = 0
    inserted_process = 0
    heap_size = [0]
    current_time = array[0].arrivalTime  # Fix: No need to use a list for current_time
    total_response_time = 0

    Heap = [None] * (4 * n)

    # Calculating the total burst time of the processes
    for i in range(n):
        total_burst_time += array[i].burstTime
        array[i].tempburstTime = array[i].burstTime

    # Inserting the processes into Heap according to arrival time
    while True:
        if inserted_process != n:
            for i in range(n):
                if array[i].arrivalTime == current_time:
                    inserted_process += 1
                    array[i].intime = -1
                    array[i].responsetime = -1
                    insert(Heap, array[i], heap_size, current_time)
        scheduling(Heap, array, n, heap_size, current_time)
        current_time += 1  # Fix: Remove the list to avoid the TypeError
        if heap_size[0] == 0 and inserted_process == n:
            break

    for i in range(n):
        total_response_time += array[i].responsetime
        total_waiting_time += (array[i].outtime - array[i].intime - array[i].tempburstTime)
        total_turnaround_time += (array[i].outtime - array[i].intime)
        total_burst_time += array[i].burstTime

    print(f"Average waiting time = {total_waiting_time / n}")
    print(f"Average response time = {total_response_time / n}")
    print(f"Average turn around time = {total_turnaround_time / n}")

# Driver code
if __name__ == "__main__":
    n = 5
    a = [
        Process(1, 4, 2, 6),
        Process(4, 5, 1, 3),
        Process(2, 5, 3, 1),
        Process(3, 1, 4, 2),
        Process(5, 3, 5, 4)
    ]
    priority(a, n)
#this code is contributed by Kishan

Output
process id = 3 current time = 1
process id = 3 current time = 2
process id = 5 current time = 3
process id = 1 current time = 4
process id = 4 current time = 5
process id = 4 current time = 6
process ...

Drawbacks of Preemptive Priority Scheduling Algorithm:

One of the most common drawbacks of the Preemptive priority CPU scheduling algorithm is the Starvation Problem. This is the problem in which a process has to wait for a longer amount of time to get scheduled into the CPU. This condition is called the starvation problem.
Example: In Example 2, we can see that process P1 is having Priority 3 and we have pre-empted the process P1 and allocated the CPU to P5. Here we are only having 7 processes.
Now, if suppose we have many processes whose priority is higher than P1, then P1 needs to wait for a longer time for the other process to be pre-empted and scheduled by the CPU. This condition is called a starvation problem.
Solution: The solution to this Starvation problem is Ageing. This can be done by decrementing the priority number by a certain number of a particular process which is waiting for a longer period of time after a certain interval.
After every 3 units of time, all the processes which are in waiting for the state, the priority of those processes will be decreased by 2, So, if there is a process P1 which is having priority 5, after waiting for 3 units of time its priority will be decreased from 5 to 3 so that if there is any process P2 which is having priority as 4 then that process P2 will wait and P1 will be scheduled and executed.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads