Priority Scheduling Algorithm in OS with Examples and Programs!

Hi Friends! Today, we are going to explain about what is priority scheduling algorithm in OS and its examples; involving with different types of priority scheduling and priority scheduling Algorithm program in C, C++, and Java with their output. This is unique article over the internet. So we make sure that at the end of this post; you will definitely fully educated about Priority Scheduling Algorithm in Operating System without getting any hassle.

What is Priority Scheduling in OS?

Priority Scheduling is a type of CPU scheduling algorithm that is used in operating systems to allocate system resources, such as CPU time, to different processes. In this algorithm, each process is assigned a priority value, usually an integer value that determines the importance or urgency of the process and the order in which it should be scheduled for execution.

Priority-Scheduling-Algorithm-in-OS

The basic principle of priority scheduling is that higher priority processes should be executed first, and lower priority processes should only be executed when there are no higher priority processes waiting. If two or more processes have the same priority, then they are scheduled in a round-robin scheduling algorithm.

Priority-Scheduling-in-OS

Work Flow of Priority Scheduling

Priority scheduling algorithm can be implemented using a variety of data structures such as arrays, linked lists, and heaps. However, it is important to ensure that the priorities of different processes are properly managed to avoid starvation, where lower priority processes are never executed due to the constant arrival of higher priority processes.

‘Priority Scheduling’ Tutorial Headlines:

In this section, we will show you all headlines about this entire article; you can check them as your choice; below shown all:

  1. What is Priority Scheduling in OS?
  2. What are the Different Types of Priority Scheduling?
  • Preemptive Priority Scheduling
  • Non Pre-Emptive Priority Scheduling
  • Dynamic Priority Scheduling
  • Static Priority Scheduling
  1. What is Pre-Emptive Vs Non Pre-Emptive Priority Scheduling?
  2. Static Vs Dynamic Priority Scheduling in OS
  3. Priority Scheduling Algorithm Example
  4. Real Life Example of Priority Scheduling
  5. What are the Advantages and Disadvantages of Priority Scheduling?
  • Advantages of Priority Scheduling Algorithm
  • Disadvantages of Priority Scheduling Algorithm
  1. Characteristics of Priority Scheduling
  2. Priority Scheduling Algorithm Program in C with Arrival Time
  3. Priority Scheduling Algorithm Program in C++
  4. Priority Scheduling Algorithm Program in Java

Let’s Get Started!!

What are the Different Types of Priority Scheduling?

There are different types of priority scheduling algorithms, including:

Also Read: First Come First Serve (FCFS) Scheduling Algorithm in OS with Examples & Programs!!

Preemptive Priority Scheduling:

Preemptive priority scheduling is a variant of process scheduling algorithm that is going to use in operating systems. In this algorithm, each process is assigned a priority level, and the process with the highest priority is given control of the CPU first.

In pre-emptive priority scheduling, if a higher-priority process becomes available while a lower-priority process is running, the lower-priority process is pre-empted and the higher-priority process is given control of the CPU. This allows for important tasks to be executed quickly and efficiently.

Pre-emptive priority scheduling is commonly used in real-time systems, where certain tasks must be completed within specific time constraints. For example, in a system that controls an assembly line, it is important that tasks related to safety and critical functions are given the highest priority to ensure that the system operates correctly.

Non Pre-Emptive Priority Scheduling:

In Non-preemptive priority scheduling, the processes are scheduled according to their priorities. Each process is assigned a priority, which determines the order in which the processes are executed. The higher the priority, the earlier the process is executed.

In this priority scheduling, once a process is scheduled to run, it continues to run until it completes its execution or it enters into a waiting state, such as waiting for I/O or waiting for a resource. At this point, the CPU scheduler selects the next process with the highest priority to run.

Dynamic Priority Scheduling:

Dynamic Priority Scheduling is used in many types of operating systems to determine the order in which processes should be executed by the CPU. In this algorithm, each process is assigned a priority level that can be changed dynamically based on various criteria, such as the amount of CPU time the process has already consumed or the importance of the process to the system.

The algorithm works by maintaining a ready queue of processes and selecting the process with the highest priority to execute next. When a process enters the ready queue, its priority is initially set based on some criteria, such as its process type, memory requirements, or user-defined parameters. As the process runs, its priority may change based on various factors such as the amount of CPU time it has already consumed or the number of I/O requests it has made.

The key advantage of dynamic priority scheduling is that it allows the system to give more priority to processes that are more important at a given time, ensuring that critical processes are executed in a timely manner. However, this algorithm also requires careful design and tuning to prevent starvation or other issues that may arise when certain processes are always given priority over others.

Static Priority Scheduling:

Static priority scheduling is a scheduling algorithm used in operating systems to determine the order in which processes are executed. In this algorithm, each process is assigned a priority value based on its characteristics, such as its importance, the amount of resources it requires, and its deadline. Processes with higher priority values are executed before processes with lower priority values.

The priority value of a process is usually fixed and does not change during its lifetime. This means that a high-priority process can potentially monopolize the CPU and prevent lower-priority processes from executing, leading to a phenomenon known as priority inversion.

To avoid priority inversion, some static priority scheduling algorithms use priority inheritance, which temporarily boosts the priority of a low-priority process when it is, blocked waiting for a resource held by a high-priority process. This ensures that the high-priority process releases the resource as soon as possible, allowing the low-priority process to continue execution without being blocked for a long time.

So, static priority scheduling can be an effective scheduling algorithm for certain types of systems where the characteristics of processes are well-defined and predictable. However, it may not be suitable for systems with dynamically changing workloads or real-time requirements, as these can cause unpredictable behaviour and can lead to poor system performance.

Overall, the choice of priority scheduling algorithm depends on the specific requirements and characteristics of the system and the processes to be scheduled.

What is Pre-Emptive Vs Non Pre-Emptive Priority Scheduling?

Preemptive and non-preemptive priority scheduling are two different scheduling algorithms that are going to use in operating systems to determine which process gets to use the CPU first based on its priority.

Also Read: Process Life Cycle in Operating System | Process State in OS

Pre-emptive priority scheduling allows higher priority processes to interrupt lower priority processes that are currently using the CPU. When a higher priority process becomes available, it can pre-empt the currently running process and take control of the CPU. This means that the CPU may switch between processes more frequently and can lead to a higher overall throughput. However, it can also result in lower response times for lower priority processes as they may have to wait longer for the CPU.

On the other hand, non-pre-emptive priority scheduling assigns priorities to processes but does not allow higher priority processes to interrupt lower priority processes that are currently using the CPU. Once a process has the CPU, it will continue to run until it finishes, is blocked, or voluntarily yields the CPU. This can result in longer response times for high-priority processes as they may have to wait for lower priority processes to finish before they can use the CPU.

In the last, pre-emptive priority scheduling can result in higher throughput but lower response times for lower priority processes, while non-pre-emptive priority scheduling can result in longer response times for high-priority processes but more predictable behaviour for lower priority processes. The choice of scheduling algorithm depends on the specific requirements and constraints of the system being designed.

Static Vs Dynamic Priority Scheduling in OS

Static and dynamic priority scheduling are two different approaches to scheduling tasks or processes in a computer system based on their priority.

Also Read: Multiprogramming Operating System: Example, Types, and Advantage!!

Static priority scheduling assigns a fixed priority level to each task or process when it is created, and this priority level does not change throughout the execution of the task. Tasks with higher priority levels are scheduled to run before tasks with lower priority levels. Static priority scheduling can be implemented using pre-emptive or non-pre-emptive algorithms. In pre-emptive static priority scheduling, a task with a higher priority can interrupt the execution of a lower-priority task, while in non-pre-emptive static priority scheduling, a task with a higher priority can only run after the lower-priority task has completed.

Dynamic priority scheduling, on the other hand, adjusts the priority level of a task dynamically based on certain factors such as the amount of CPU time a task has consumed or the amount of time it has spent waiting in the queue. Tasks that have been waiting for a longer time or have used less CPU time are given higher priority levels to ensure fairness and prevent starvation. Dynamic priority scheduling is typically implemented using pre-emptive algorithms.

Static priority scheduling can provide predictable behaviour and can be easier to implement, but it may not be well-suited for systems with changing workloads or resource requirements. Dynamic priority scheduling can be more flexible and fair, but it can also be more complex to implement and may require more overhead. The choice between static and dynamic priority scheduling depends on the specific requirements of the system and the workload it needs to handle.

Priority Scheduling Algorithm Example

Sure, here’s an example of Priority Scheduling algorithm with arrival time:

Also Read: Multitasking Operating System? Example, Types, and Advantages!!

Consider the following set of processes with their arrival time, burst time and priority:

Process        Arrival Time              Burst Time       Priority

P1                       0                                         5                  3

P2                       1                                         3                  1

P3                       2                                         3                  2

P4                       4                                         1                  4

P5                      5                                         2                  5

The priority value indicates the priority of each process, where a lower number indicates a higher priority. In this case, Process P2 has the highest priority, followed by P3, P1, P4, and P5 in that order.

Using Priority Scheduling algorithm, the processes are scheduled based on their priority, where the process with the highest priority is executed first. In case of a tie in priority, the process with the earliest arrival time is executed first.

Here’s how the scheduling will occur:

Process                  Arrival Time         Burst Time           Priority    Completion Time   Turnaround Time   Waiting Time

P2                           1                              3                              1                              4                              3                              0

P3                           2                              3                              2                              7                              5                              2

P1                           0                              5                              3                              12                           12                           7

P4                           4                              1                              4                              13                           9                              8

P5                           5                              2                              5                              15                           10                           8

The first process to be executed is P2, as it has the highest priority of 1 and arrives before P3. After P2 completes, P3 is executed, followed by P1, P4, and P5. The completion time, turnaround time, and waiting time for each process are also calculated as shown in the table above.

Real Life Example of Priority Scheduling

A real-life example of priority scheduling can be seen in an airport where flights are given priority based on their urgency. For instance, a medical emergency may arise where a patient needs to be transported to a hospital as soon as possible. In such cases, the airport may give priority to the medical evacuation flight over other flights waiting to take off or land. Similarly, flights carrying important government officials, military personnel, or VIPs may also be given priority over other flights.

In the context of a computer system, priority scheduling is used to ensure that high-priority tasks are completed quickly, while low-priority tasks are executed only when there is spare processing time available. For example, if a computer system is running multiple processes, a process that needs to be completed urgently, such as printing a document or running a critical system task, will be assigned a higher priority than a process that can wait, such as running backup or updating software. This helps to ensure that the critical process is completed in a timely manner, even if the system is busy with other tasks.

What are the Advantages and Disadvantages of Priority Scheduling?

Priority scheduling is a CPU scheduling algorithm where the process with the highest priority is scheduled for execution first. There are several of the advantages and disadvantages of priority scheduling:

Advantages of Priority Scheduling Algorithm

Here are some advantages/benefits of the priority scheduling algorithm:

Also Read: Batch Processing Operating System: Examples, Advantage, & Disadvantage!!

Better Throughput: The priority scheduling algorithm can improve system throughput by ensuring that high-priority processes are executed first. This can help to reduce the average waiting time for processes and make the system more responsive.

Efficient Use of Resources: The priority scheduling algorithm can help to make more efficient use of system resources by giving higher priority to important processes. This can ensure that critical processes are completed quickly, while lower-priority processes are executed later.

Flexibility: The priority scheduling algorithm is flexible and can be adapted to suit different types of systems. It can be used in both pre-emptive and non-pre-emptive modes, and priorities can be assigned dynamically based on the needs of the system.

Fairness: The priority scheduling algorithm can ensure fairness by assigning priorities based on the importance of the process. This can help to prevent low-priority processes from being starved of resources and ensure that all processes get their fair share of CPU time.

Real-Time Systems: Priority scheduling is particularly useful in real-time systems, where response times are critical. Real-time systems often have strict deadlines, and priority scheduling can help to ensure that high-priority tasks are completed on time.

Overall, the priority scheduling algorithm can improve system performance and responsiveness by ensuring that critical processes are executed first. It can also help to make more efficient use of system resources and ensure fairness by assigning priorities based on the importance of the process.

Disadvantages of Priority Scheduling Algorithm

While this algorithm has many advantages, there are also some disadvantages that can affect its performance. Some of these disadvantages include:

Starvation: In priority scheduling, there is a risk of starvation where a low-priority process may not get a chance to execute for a long time, as higher-priority processes keep getting scheduled first. This can result in poor performance for the low-priority process and a reduced overall system throughput.

Indefinite Blocking: If a high-priority process continuously arrives in the queue, low-priority processes may never get executed. This is known as indefinite blocking and can result in a situation where the low-priority process is never scheduled.

Complexity: Priority scheduling is more complex than other scheduling algorithms. The operating system must constantly monitor and adjust priorities to ensure that the most important processes are executed first. This can be time-consuming and may require additional processing power.

Prioritization Errors: If priorities are not set correctly, it can lead to problems where lower-priority processes take up resources that should be allocated to higher-priority processes. This can result in performance issues and reduced system efficiency.

Inefficient Use of Resources: If a high-priority process completes quickly and is followed by a series of low-priority processes, it may result in inefficient use of system resources. This is because the high-priority process may have been given more resources than it needed, leaving fewer resources available for the low-priority processes.

Characteristics of Priority Scheduling 

Here are some characteristics of the priority scheduling algorithm, as follow them:

Also Read: What is Deadlock in OS with Example? Deadlock Handling in Operating System!

Preemptive and Non-Preemptive: Priority scheduling algorithm can be preemptive or non-preemptive. In the preemptive priority scheduling algorithm, a running process can be interrupted by a higher priority process. In the non-preemptive priority scheduling algorithm, the running process will continue until it completes or blocks on I/O, even if a higher priority process arrives.

Dynamic and Static: Priority scheduling algorithm can be dynamic or static. In the dynamic priority scheduling algorithm, the priority of a process can change during its execution based on the changing requirements of the system or the process itself. In the static priority scheduling algorithm, the priority of a process is fixed and does not change during its execution.

Starvation: Priority scheduling algorithm can suffer from starvation if a process with a low priority never gets a chance to execute because higher priority processes keep arriving. To avoid starvation, some algorithms use aging, which increases the priority of a process as it waits.

Performance: The performance of the priority scheduling algorithm depends on the method used to assign priorities to processes. If the priorities are assigned in a way that reflects the importance of the processes, the algorithm can provide good performance. However, if the priorities are assigned in a way that is arbitrary or biased, the algorithm can lead to poor performance.

Complexity: Priority scheduling algorithm can be more complex than other scheduling algorithms because it requires maintaining a priority queue of processes. This can increase the overhead of the scheduler and reduce the overall system performance.

Priority Scheduling Algorithm Program in C with Arrival Time

Here, w show you a Priority Scheduling Algorithm program in C that takes into account arrival time:

#include<stdio.h>

#include<stdlib.h>

struct process {

    int process_id;

    int arrival_time;

    int burst_time;

    int priority;

};

void sort(struct process p[], int n) {

    int i, j;

    struct process temp;

    for(i = 0; i < n; i++) {

        for(j = i+1; j < n; j++) {

            if(p[i].arrival_time > p[j].arrival_time) {

                temp = p[i];

                p[i] = p[j];

                p[j] = temp;

            }

        }

    }

}

void priority_scheduling(struct process p[], int n) {

    int i, j, t, total_time = 0;

    float avg_wt = 0, avg_tat = 0;

    sort(p, n);

    printf(“\nProcess ID\tArrival Time\tBurst Time\tPriority\tWaiting Time\tTurnaround Time”);

    for(i = 0; i < n; i++) {

        t = total_time;

        for(j = i+1; j < n; j++) {

            if(p[j].arrival_time <= total_time) {

                if(p[j].priority < p[i].priority) {

                    struct process temp = p[i];

                    p[i] = p[j];

                    p[j] = temp;

                }

            } else {

                break;

            }

        }

        total_time += p[i].burst_time;

        printf(“\n%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d”, p[i].process_id, p[i].arrival_time, p[i].burst_time, p[i].priority, total_time-t-p[i].burst_time, total_time-p[i].arrival_time);

        avg_wt += total_time-t-p[i].burst_time;

        avg_tat += total_time-p[i].arrival_time;

    }

    avg_wt /= n;

    avg_tat /= n;

    printf(“\n\nAverage waiting time: %f”, avg_wt);

    printf(“\nAverage turnaround time: %f”, avg_tat);

}

int main() {

    int i, n;

    printf(“Enter the number of processes: “);

    scanf(“%d”, &n);

    struct process p[n];

    for(i = 0; i < n; i++) {

        printf(“\nEnter details for process %d:\n”, i+1);

        printf(“Enter arrival time: “);

        scanf(“%d”, &p[i].arrival_time);

        printf(“Enter burst time: “);

        scanf(“%d”, &p[i].burst_time);

        printf(“Enter priority: “);

        scanf(“%d”, &p[i].priority);

        p[i].process_id = i+1;

    }

    priority_scheduling(p, n);

    return 0;

}

In this program, we first define a process structure to store the details of each process, including the process ID, arrival time, burst time, and priority.

We then define a sort function to sort the processes based on their arrival time. This function uses a simple bubble sort algorithm to sort the processes in ascending order of arrival time.

The priority_scheduling function implements the priority scheduling algorithm. We first call the sort function to sort the processes based on their arrival time. We then iterate over each process in the sorted array, and for each process, we iterate over the remaining processes to find any processes that arrive before the current process completes. If we find such a process, we compare its priority with the current process, and if it has

Priority Scheduling Algorithm Program in C++

Sure! Here’s an example implementation of the Priority Scheduling Algorithm in C++:

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

// Struct for storing process information

struct Process {

    int pid; // Process ID

    int burst_time; // Burst time of the process

    int priority; // Priority of the process

};

// Function to compare processes based on priority

bool compare(Process p1, Process p2) {

    return p1.priority < p2.priority;

}

// Function to calculate waiting time and turnaround time for each process

void calculateTimes(vector<Process>& processes, vector<int>& waiting_time, vector<int>& turnaround_time) {

    int n = processes.size();

    waiting_time[0] = 0;

    turnaround_time[0] = processes[0].burst_time;

    // Calculate waiting time and turnaround time for each process

    for (int i = 1; i < n; i++) {

        waiting_time[i] = waiting_time[i-1] + processes[i-1].burst_time;

        turnaround_time[i] = waiting_time[i] + processes[i].burst_time;

    }

}

// Function to calculate average waiting time and average turnaround time

void calculateAverages(vector<Process>& processes, vector<int>& waiting_time, vector<int>& turnaround_time, double& avg_waiting_time, double& avg_turnaround_time) {

    int n = processes.size();

    int total_waiting_time = 0, total_turnaround_time = 0;

    // Calculate total waiting time and total turnaround time

    for (int i = 0; i < n; i++) {

        total_waiting_time += waiting_time[i];

        total_turnaround_time += turnaround_time[i];

    }

    // Calculate average waiting time and average turnaround time

    avg_waiting_time = (double)total_waiting_time / n;

    avg_turnaround_time = (double)total_turnaround_time / n;

}

// Priority Scheduling Algorithm function

void priorityScheduling(vector<Process>& processes) {

    int n = processes.size();

    // Sort processes based on priority

    sort(processes.begin(), processes.end(), compare);

    vector<int> waiting_time(n);

    vector<int> turnaround_time(n);

    double avg_waiting_time, avg_turnaround_time;

    calculateTimes(processes, waiting_time, turnaround_time);

    calculateAverages(processes, waiting_time, turnaround_time, avg_waiting_time, avg_turnaround_time);

    // Display process information and calculated times

    cout << “Process\tBurst Time\tPriority\tWaiting Time\tTurnaround Time\n”;

    for (int i = 0; i < n; i++) {

        cout << processes[i].pid << “\t\t” << processes[i].burst_time << “\t\t” << processes[i].priority << “\t\t” << waiting_time[i] << “\t\t” << turnaround_time[i] << endl;

    }

    cout << “Average Waiting Time: ” << avg_waiting_time << endl;

    cout << “Average Turnaround Time: ” << avg_turnaround_time << endl;

}

int main() {

    vector<Process> processes = {{1, 10, 2}, {2, 5, 1}, {3, 8, 3}, {4, 3, 4}};

    priorityScheduling(processes);

    return 0;

}

In this program, the Process struct is used to store information about each process, including its process ID, burst time, and priority. The compare function is used to compare processes based on their priority, which is used to sort the processes in ascending order before running the algorithm. The `calculate

Priority Scheduling Algorithm Program in Java

Sure, here’s an example of a Priority Scheduling Algorithm program in Java:

import java.util.*;

class Process {

    int pid;

    int burstTime;

    int priority;

        public Process(int pid, int burstTime, int priority) {

        this.pid = pid;

        this.burstTime = burstTime;

        this.priority = priority;

    }

}

class PriorityScheduling {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print(“Enter the number of processes: “);

        int n = sc.nextInt();

         List<Process> processes = new ArrayList<>();

         for (int i = 1; i <= n; i++) {

            System.out.print(“Enter the burst time of process ” + i + “: “);

            int burstTime = sc.nextInt();

            System.out.print(“Enter the priority of process ” + i + “: “);

            int priority = sc.nextInt();

            Process p = new Process(i, burstTime, priority);

            processes.add(p);

        }

                // sort the processes based on priority (higher priority first)

        Collections.sort(processes, new Comparator<Process>() {

            @Override

            public int compare(Process p1, Process p2) {

                return Integer.compare(p2.priority, p1.priority);

            }

        });

        int currentTime = 0;

        int totalWaitingTime = 0;

        System.out.println(“\nProcess Execution Order:”);

        System.out.println(“PID\tBurst Time\tPriority\tWaiting Time”);

         for (Process p : processes) {

            int waitingTime = currentTime;

            System.out.println(p.pid + “\t” + p.burstTime + “\t\t” + p.priority + “\t\t” + waitingTime);

            totalWaitingTime += waitingTime;

            currentTime += p.burstTime;

        }

                double averageWaitingTime = (double) totalWaitingTime / n;

        System.out.println(“\nAverage waiting time: ” + averageWaitingTime);

    }

}

Here, the Process class represents a process with a unique process ID (pid), a burst time (burstTime), and a priority (priority). The PriorityScheduling class is where the main program logic is implemented.

First, the user is prompted to enter the number of processes to be scheduled. Then, the program asks for the burst time and priority of each process, and creates a Process object for each process.

Next, the processes are sorted based on their priority using the Collections.sort() method with a custom Comparator that compares the priorities of two processes.

Then, the program executes the processes in the order of their priority, calculating the waiting time for each process and keeping track of the total waiting time. Finally, the average waiting time is calculated and displayed.

Final Verdicts

Now we hope that you have fully understood about what is priority scheduling algorithm in OS and its example; involving with different types of priority scheduling and priority scheduling Algorithm program in C, C++, and Java with their output. If this post is helpful for you, then please share it along with your friends, family members or relatives over social media platforms like as Facebook, Instagram, Linked In, Twitter, and more.

Also Read: Single User Operating System: Example, Advantages, & Disadvantages!!

If you have any experience, tips, tricks, or query regarding this issue? You can drop a comment!

Happy Learning!!

Leave a Reply

Your email address will not be published. Required fields are marked *