Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Aptitude
  • Engineering Mathematics
  • Discrete Mathematics
  • Operating System
  • DBMS
  • Computer Networks
  • Digital Logic and Design
  • C Programming
  • Data Structures
  • Algorithms
  • Theory of Computation
  • Compiler Design
  • Computer Org and Architecture
Open In App
Next Article:
Priority Scheduling in Operating System
Next article icon

Program for Priority CPU Scheduling | Set 1

Last Updated : 14 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Priority scheduling is one of the most common scheduling algorithms in batch systems. Each process is assigned a priority. The process with the highest priority is to be executed first and so on. Processes with the same priority are executed on a first-come first served basis. Priority can be decided based on memory requirements, time requirements or any other resource requirement. Also priority can be decided on the ratio of average I/O to average CPU burst time.

Implementation: 

1- First input the processes with their burst time      and priority.  2- Sort the processes, burst time and priority     according to the priority.  3- Now simply apply FCFS algorithm.

prior

Note: A major problem with priority scheduling is indefinite blocking or starvation. A solution to the problem of indefinite blockage of the low-priority process is aging. Aging is a technique of gradually increasing the priority of processes that wait in the system for a long period of time.

C++




// C++ program for implementation of FCFS
// scheduling
#include <bits/stdc++.h>
using namespace std;
  
struct Process {
    int pid; // Process ID
    int bt; // CPU Burst time required
    int priority; // Priority of this process
};
  
// Function to sort the Process acc. to priority
bool comparison(Process a, Process b)
{
    return (a.priority > b.priority);
}
  
// Function to find the waiting time for all
// processes
void findWaitingTime(Process proc[], int n, int wt[])
{
    // waiting time for first process is 0
    wt[0] = 0;
  
    // calculating waiting time
    for (int i = 1; i < n; i++)
        wt[i] = proc[i - 1].bt + wt[i - 1];
}
  
// Function to calculate turn around time
void findTurnAroundTime(Process proc[], int n, int wt[],
                        int tat[])
{
    // calculating turnaround time by adding
    // bt[i] + wt[i]
    for (int i = 0; i < n; i++)
        tat[i] = proc[i].bt + wt[i];
}
  
// Function to calculate average time
void findavgTime(Process proc[], int n)
{
    int wt[n], tat[n], total_wt = 0, total_tat = 0;
  
    // Function to find waiting time of all processes
    findWaitingTime(proc, n, wt);
  
    // Function to find turn around time for all processes
    findTurnAroundTime(proc, n, wt, tat);
  
    // Display processes along with all details
    cout << "\nProcesses  "
         << " Burst time  "
         << " Waiting time  "
         << " Turn around time\n";
  
    // Calculate total waiting time and total turn
    // around time
    for (int i = 0; i < n; i++) {
        total_wt = total_wt + wt[i];
        total_tat = total_tat + tat[i];
        cout << "   " << proc[i].pid << "\t\t" << proc[i].bt
             << "\t    " << wt[i] << "\t\t  " << tat[i]
             << endl;
    }
  
    cout << "\nAverage waiting time = "
         << (float)total_wt / (float)n;
    cout << "\nAverage turn around time = "
         << (float)total_tat / (float)n;
}
  
void priorityScheduling(Process proc[], int n)
{
    // Sort processes by priority
    sort(proc, proc + n, comparison);
  
    cout << "Order in which processes gets executed \n";
    for (int i = 0; i < n; i++)
        cout << proc[i].pid << " ";
  
    findavgTime(proc, n);
}
  
// Driver code
int main()
{
    Process proc[]
        = { { 1, 10, 2 }, { 2, 5, 0 }, { 3, 8, 1 } };
    int n = sizeof proc / sizeof proc[0];
    priorityScheduling(proc, n);
    return 0;
}
 
 

Java




// Java program for implementation of FCFS
// scheduling
import java.util.*;
  
class Process {
    int pid; // Process ID
    int bt; // CPU Burst time required
    int priority; // Priority of this process
    Process(int pid, int bt, int priority)
    {
        this.pid = pid;
        this.bt = bt;
        this.priority = priority;
    }
    public int prior() { return priority; }
}
  
public class GFG {
  
    // Function to find the waiting time for all
    // processes
    public void findWaitingTime(Process proc[], int n,
                                int wt[])
    {
  
        // waiting time for first process is 0
        wt[0] = 0;
  
        // calculating waiting time
        for (int i = 1; i < n; i++)
            wt[i] = proc[i - 1].bt + wt[i - 1];
    }
  
    // Function to calculate turn around time
    public void findTurnAroundTime(Process proc[], int n,
                                   int wt[], int tat[])
    {
        // calculating turnaround time by adding
        // bt[i] + wt[i]
        for (int i = 0; i < n; i++)
            tat[i] = proc[i].bt + wt[i];
    }
  
    // Function to calculate average time
    public void findavgTime(Process proc[], int n)
    {
        int wt[] = new int[n], tat[] = new int[n],
            total_wt = 0, total_tat = 0;
  
        // Function to find waiting time of all processes
        findWaitingTime(proc, n, wt);
  
        // Function to find turn around time for all
        // processes
        findTurnAroundTime(proc, n, wt, tat);
  
        // Display processes along with all details
        System.out.print(
            "\nProcesses   Burst time   Waiting time   Turn around time\n");
  
        // Calculate total waiting time and total turn
        // around time
        for (int i = 0; i < n; i++) {
            total_wt = total_wt + wt[i];
            total_tat = total_tat + tat[i];
            System.out.print(" " + proc[i].pid + "\t\t"
                             + proc[i].bt + "\t " + wt[i]
                             + "\t\t " + tat[i] + "\n");
        }
  
        System.out.print("\nAverage waiting time = "
                         + (float)total_wt / (float)n);
        System.out.print("\nAverage turn around time = "
                         + (float)total_tat / (float)n);
    }
  
    public void priorityScheduling(Process proc[], int n)
    {
  
        // Sort processes by priority
        Arrays.sort(proc, new Comparator<Process>() {
            @Override
            public int compare(Process a, Process b)
            {
                return b.prior() - a.prior();
            }
        });
        System.out.print(
            "Order in which processes gets executed \n");
        for (int i = 0; i < n; i++)
            System.out.print(proc[i].pid + " ");
  
        findavgTime(proc, n);
    }
  
    // Driver code
    public static void main(String[] args)
    {
        GFG ob = new GFG();
        int n = 3;
        Process proc[] = new Process[n];
        proc[0] = new Process(1, 10, 2);
        proc[1] = new Process(2, 5, 0);
        proc[2] = new Process(3, 8, 1);
        ob.priorityScheduling(proc, n);
    }
}
  
// This code is contributed by rahulpatil07109.
 
 

Python3




# Python3 program for implementation of
# Priority Scheduling
  
# Function to find the waiting time
# for all processes
  
  
def findWaitingTime(processes, n, wt):
    wt[0] = 0
  
    # calculating waiting time
    for i in range(1, n):
        wt[i] = processes[i - 1][1] + wt[i - 1]
  
# Function to calculate turn around time
  
  
def findTurnAroundTime(processes, n, wt, tat):
  
    # Calculating turnaround time by
    # adding bt[i] + wt[i]
    for i in range(n):
        tat[i] = processes[i][1] + wt[i]
  
# Function to calculate average waiting
# and turn-around times.
  
  
def findavgTime(processes, n):
    wt = [0] * n
    tat = [0] * n
  
    # Function to find waiting time
    # of all processes
    findWaitingTime(processes, n, wt)
  
    # Function to find turn around time
    # for all processes
    findTurnAroundTime(processes, n, wt, tat)
  
    # Display processes along with all details
    print("\nProcesses    Burst Time    Waiting",
          "Time    Turn-Around Time")
    total_wt = 0
    total_tat = 0
    for i in range(n):
  
        total_wt = total_wt + wt[i]
        total_tat = total_tat + tat[i]
        print(" ", processes[i][0], "\t\t",
              processes[i][1], "\t\t",
              wt[i], "\t\t", tat[i])
  
    print("\nAverage waiting time = %.5f " % (total_wt / n))
    print("Average turn around time = ", total_tat / n)
  
  
def priorityScheduling(proc, n):
  
    # Sort processes by priority
    proc = sorted(proc, key=lambda proc: proc[2],
                  reverse=True)
  
    print("Order in which processes gets executed")
    for i in proc:
        print(i[0], end=" ")
    findavgTime(proc, n)
  
  
# Driver code
if __name__ == "__main__":
  
    # Process id's
    proc = [[1, 10, 1],
            [2, 5, 0],
            [3, 8, 1]]
    n = 3
    priorityScheduling(proc, n)
  
# This code is contributed
# Shubham Singh(SHUBHAMSINGH10)
 
 

Javascript




// JavaScript program for implementation of Priority Scheduling
class Process {
    constructor(pid, bt, priority) {
        this.pid = pid; // Process ID
        this.bt = bt; // CPU Burst time required
        this.priority = priority; // Priority of this process
    }
  
    prior() {
        return this.priority;
    }
}
  
class GFG {
    // Function to find the waiting time for all processes
    findWaitingTime(proc, n, wt) {
        // waiting time for first process is 0
        wt[0] = 0;
        // calculating waiting time
        for (let i = 1; i < n; i++) {
            wt[i] = proc[i - 1].bt + wt[i - 1];
        }
    }
  
    // Function to calculate turn around time
    findTurnAroundTime(proc, n, wt, tat) {
        // calculating turnaround time by adding bt[i] + wt[i]
        for (let i = 0; i < n; i++) {
            tat[i] = proc[i].bt + wt[i];
        }
    }
  
    // Function to calculate average time
    findavgTime(proc, n) {
        let wt = new Array(n);
        let tat = new Array(n);
        let total_wt = 0;
        let total_tat = 0;
        // Function to find waiting time of all processes
        this.findWaitingTime(proc, n, wt);
  
        // Function to find turn around time for all processes
        this.findTurnAroundTime(proc, n, wt, tat);
  
        // Display processes along with all details
        console.log("Processes   Burst time   Waiting time   Turn around time");
  
        // Calculate total waiting time and total turn around time
        for (let i = 0; i < n; i++) {
            total_wt = total_wt + wt[i];
            total_tat = total_tat + tat[i];
            console.log(
                " " + proc[i].pid + "\t\t" + proc[i].bt + "\t " + wt[i] + "\t\t " + tat[i]
            );
        }
  
        console.log(
            "Average waiting time = " + total_wt / n
        );
        console.log(
            "Average turn around time = " + total_tat / n
        );
    }
  
    priorityScheduling(proc, n) {
        // Sort processes by priority
        proc.sort((a, b) => b.prior() - a.prior());
        console.log("Order in which processes get executed:");
        for (let i = 0; i < n; i++) {
            console.log(proc[i].pid + " ");
        }
  
        this.findavgTime(proc, n);
    }
}
  
// Driver code
let ob = new GFG();
let n = 3;
let proc = [];
proc[0] = new Process(1, 10, 2);
proc[1] = new Process(2, 5, 0);
proc[2] = new Process(3, 8, 1);
ob.priorityScheduling(proc, n);
//This code is Contributed by chinmaya121221
 
 

C#




using System;
using System.Collections.Generic;
  
 class Process
{
public int pid; // Process ID
    public int bt; // CPU Burst time required
    public int priority; // Priority of this process
public Process(int pid, int bt, int priority)
{
    this.pid = pid;
    this.bt = bt;
    this.priority = priority;
}
  
public int Prior
{
    get { return priority; }
}
}
  
class GFG
{
// Function to find the waiting time for all processes
public void findWaitingTime(Process[] proc, int n, int[] wt)
{
// waiting time for first process is 0
wt[0] = 0;  
     // calculating waiting time
    for (int i = 1; i < n; i++)
        wt[i] = proc[i - 1].bt + wt[i - 1];
}
  
// Function to calculate turn around time
public void findTurnAroundTime(Process[] proc, int n, int[] wt, int[] tat)
{
    // calculating turnaround time by adding
    // bt[i] + wt[i]
    for (int i = 0; i < n; i++)
        tat[i] = proc[i].bt + wt[i];
}
  
// Function to calculate average time
public void findavgTime(Process[] proc, int n)
{
    int[] wt = new int[n];
    int[] tat = new int[n];
    int total_wt = 0;
    int total_tat = 0;
  
    // Function to find waiting time of all processes
    findWaitingTime(proc, n, wt);
  
    // Function to find turn around time for all processes
    findTurnAroundTime(proc, n, wt, tat);
  
    // Display processes along with all details
    Console.WriteLine("\nProcesses   Burst time   Waiting time   Turn around time");
  
    // Calculate total waiting time and total turn around time
    for (int i = 0; i < n; i++)
    {
        total_wt = total_wt + wt[i];
        total_tat = total_tat + tat[i];
        Console.WriteLine(" " + proc[i].pid + "\t\t" + proc[i].bt + "\t " + wt[i] + "\t\t " + tat[i]);
    }
  
    Console.WriteLine("\nAverage waiting time = " + (float)total_wt / (float)n);
    Console.WriteLine("Average turn around time = " + (float)total_tat / (float)n);
}
  
public void priorityScheduling(Process[] proc, int n)
{
    // Sort processes by priority
    Array.Sort(proc, new Comparison<Process>((a, b) => b.Prior.CompareTo(a.Prior)));
    Console.WriteLine("Order in which processes gets executed ");
  
    for (int i = 0; i < n; i++)
        Console.Write(proc[i].pid + " ");
  
    findavgTime(proc, n);
}
  
// Driver code
static void Main(string[] args)
{
    GFG ob = new GFG();
    int n = 3;
    Process[] proc = new Process[n];
    proc[0] = new Process(1, 10, 2);
    proc[1] = new Process(2, 5, 0);
    proc[2] = new Process(3, 8, 1);
    ob.priorityScheduling(proc, n);
}
} 
 
 

Output:

Order in which processes gets executed   1 3 2   Processes  Burst time  Waiting time  Turn around time   1        10     0         10   3        8     10         18   2        5     18         23    Average waiting time = 9.33333  Average turn around time = 17

Advantages:

  • Priority-based scheduling ensures that high-priority processes are executed first, which can lead to faster completion of critical tasks.
  • Priority scheduling is useful for real-time systems that require processes to meet strict timing constraints.
  • Priority scheduling can reduce the average waiting time for processes that require a significant amount of CPU time.

Disadvantages:

  • Priority inversion: Priority inversion occurs when a low-priority process holds a resource that a high-priority process requires. This can cause delays in the execution of high-priority processes.
  • Starvation: If the system is heavily loaded with high-priority processes, low-priority processes may never get a chance to execute.
  • Priority inversion avoidance techniques, such as priority inheritance or priority ceiling protocols, can introduce additional complexity to the system.
  • Setting priorities can be a difficult task, especially when there are many processes with different priorities.

In this post, the processes with arrival time 0 are discussed. In the next set, we will be considering different arrival times to evaluate waiting times.



Next Article
Priority Scheduling in Operating System

S

Sahil Chhabra (akku)
Improve
Article Tags :
  • Operating Systems
  • cpu-scheduling

Similar Reads

  • Program for FCFS CPU Scheduling | Set 1
    First come - First served (FCFS), is the simplest scheduling algorithm. FIFO simply queues processes according to the order they arrive in the ready queue. In this algorithm, the process that comes first will be executed first and next process starts only after the previous gets fully executed. Term
    15+ min read
  • Program for Preemptive Priority CPU Scheduling
    Implementing priority CPU scheduling. In this problem, we are using Min Heap as the data structure for implementing priority scheduling. In this problem smaller numbers denote higher priority. The following functions are used in the given code below: struct process { processID, burst time, response
    15+ min read
  • Program for HRRN CPU Scheduling Algorithm
    The Highest Response Ratio Next (HRRN) scheduling algorithm is a non-preemptive scheduling technique used in operating systems to manage the execution of processes. It is designed to improve upon simpler algorithms like First-Come-First-Serve (FCFS) and Shortest Job Next (SJN) by balancing both the
    15 min read
  • Priority Scheduling in Operating System
    Priority scheduling is one of the most common scheduling algorithms used by the operating system to schedule processes based on their priority. Each process is assigned a priority. The process with the highest priority is to be executed first and so on. Processes with the same priority are executed
    4 min read
  • Selfish Round Robin CPU Scheduling
    Prerequisite - Program for Round Robin scheduling  In the traditional Round Robin scheduling algorithm, all processes were treated equally for processing. The objective of the Selfish Round Robin is to give better service to processes that have been executing for a while than to newcomers. It's a mo
    5 min read
  • Fair-share CPU scheduling
    Fair-share scheduling is a scheduling algorithm that was first designed by Judy Kay and Piers Lauder at Sydney University in the 1980s. It is a scheduling algorithm for computer operating systems that dynamically distributes the time quanta "equally" to its users. Time quantum is the processor time
    2 min read
  • Shortest Job First or SJF CPU Scheduling
    Shortest Job First (SJF) or Shortest Job Next (SJN) is a scheduling process that selects the waiting process with the smallest execution time to execute next. This scheduling method may or may not be preemptive. Significantly reduces the average waiting time for other processes waiting to be execute
    4 min read
  • Longest Remaining Time First (LRTF) CPU Scheduling Program
    We have given some processes with arrival time and Burst Time and we have to find the completion time (CT), Turn Around Time(TAT), Average Turn Around Time (Avg TAT), Waiting Time(WT), Average Waiting Time (AWT) for the given processes. Prerequisite: CPU Scheduling | Longest Remaining Time First (LR
    15+ min read
  • Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
    The shortest job first (SJF) or shortest job next, is a scheduling policy that selects the waiting process with the smallest execution time to execute next. SJN, also known as Shortest Job Next (SJN), can be preemptive or non-preemptive. Characteristics of SJF Scheduling: Shortest Job first has the
    13 min read
  • Priority CPU Scheduling with different arrival time - Set 2
    Prerequisite -Program for Priority Scheduling - Set 1Priority scheduling is a non-preemptive algorithm and one of the most common scheduling algorithms in batch systems. Each process is assigned first arrival time (less arrival time process first) if two processes have same arrival time, then compar
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences