Back

Priority Scheduling Program In C

11 Dec 2024
6 min read

Modern computer programs are growing in complexity, and managing system resources efficiently is more critical than ever. Among these resources, CPU time stands out as a finite resource that must be carefully distributed among competing processes. If not, the systems become too slow. This is where priority scheduling gets a lot of importance. These algorithms are used in operating systems, and the decision on which process to execute is based on priority levels. In this blog, we’ll break down how priority scheduling works and guide you through implementing a priority scheduling program in c.

What is Priority Scheduling Algorithm

Priority scheduling is a CPU scheduling algorithm. It selects processes for execution based on their priority levels. Each process is assigned a priority, and the CPU schedules them in descending order of priority. Processes with higher priority are executed first so that critical tasks receive CPU time sooner than other ones. There are factors like execution time and memory requirements, along with others, that often determine a process's priority. 

There are two main types of priority scheduling: preemptive and non-preemptive.

Preemptive Scheduling: 

In this approach, if a process with a higher priority arrives while another process is already executing, the currently running process is interrupted. The CPU then switches to the new process and allows the priority process to execute immediately. In this way, high-priority tasks are addressed without delay but it may also lead to frequent context switching. 

Non-preemptive Scheduling: 

In the non-preemptive method once the process starts executing it runs to completion without interruption. Even if a process with a higher priority arrives during the execution of the first process, it must wait until the current process finishes. This approach minimizes context switching. But it can lead to longer wait times for high-priority tasks.

How Prioritisation is Decided

The assigning process criteria of priorities can vary depending on the system’s requirements and objectives. The factors which influence prioritisation include:

  1. Task Importance: Critical operations such as system-level tasks or real-time applications generally are given the highest priority.
  2. Resource Requirements: Processes that need extensive system resources such as memory or I/O devices can be prioritized to give them access to these essentials without delays.
  3. Wait Time: To avoid starvation of lower-priority tasks, a process’s priority can increase if it waits for a long time for CPU time.
  4. User-Defined Priorities: Sometimes systems allow users or administrators to set custom priorities. This can be based on specific needs or workloads.
  5. Process Type: Foreground processes that involve direct user interaction are also given higher priority compared to background processes. A process that can execute without immediate attention can then take a backseat.

Examples of Priority Scheduling Algorithm

Now let’s look at an example of priority scheduling with time and priority: 

Three processes, A, B, and C, as shown in the table, run on the CPU. A preemptive priority scheduling is used to track each running program. 

Process Burst Time Arrival Time Priority
A 5 0 3
B 3 3 1
C 2 5 2

At time 0, Process A starts execution because it is the first process and has arrived. It runs for its full burst time of 5 seconds.

At time 5, Process A completes its execution. Now, both Process B and Process C are in the queue, but Process C has a higher priority (priority 2) than Process B (priority 1).

At time 5, Process C starts its execution for 2 seconds (its burst time) and finishes at time 7.

At time 7, Process B, which has the lowest priority, starts and runs for 3 seconds, completing at time 10.

Algorithm for Priority Scheduling Program in C

Now that you have an understanding of the theoretical concepts and practical examples of the priority scheduling algorithm, we can now outline the steps to implement the priority scheduling program in c:

  • Begin by taking input for the total number of processes to be executed.
  • For each process, input its burst time (execution time) and priority level.
  • Arrange the processes in descending order of priority to determine the execution sequence.
  • Compute the average waiting time and turnaround time for all processes.
  • Output the execution order of processes, along with their individual and average waiting and turnaround times.

Implementing Priority Scheduling Program in C

Here’s an example of a priority scheduling program in C with arrival time: 

  • The program asks the user to input the number of processes, along with each process's ID, burst time, and priority. The information is stored in an array of structures called proc.
  • A priority scheduling function is called, and it sorts the processes by priority using a selection sort algorithm. The sorted processes are then passed to the find average time function.
  • This function calculates the waiting time and turnaround time for each process. 
  • The program prints the process ID, burst time, priority, waiting time, and turnaround time for each process.
  • In the output, Process 2 has the highest priority and is assigned the CPU first.
  • After Process 2 completes, the CPU is assigned to Process 1 and then Process 3, based on their priority.
#include<stdio.h>  
#include<stdlib.h>  

struct process {  
    int process_id;  
    int burst_time;  
    int priority;  
    int waiting_time;  
    int turnaround_time;  
};  

void find_waiting_time(struct process[], int, int[]);  
void find_turnaround_time(struct process[], int, int[], int[]);  
void find_average_time(struct process[], int);  
void priority_scheduling(struct process[], int);  

int main()  
{  
    int n, i;  
    struct process proc[10];  

    printf("Enter the number of processes: ");  
    scanf("%d", &n);  

    for(i = 0; i< n; i++)  
    {  
        printf("\nEnter the process ID: ");  
        scanf("%d", &proc[i].process_id);  

        printf("Enter the burst time: ");  
        scanf("%d", &proc[i].burst_time);  

        printf("Enter the priority: ");  
        scanf("%d", &proc[i].priority);  
    }  

    priority_scheduling(proc, n);  
    return 0;  
}  

void find_waiting_time(struct process proc[], int n, int wt[])  
{  
    int i;  
    wt[0] = 0;  

    for(i = 1; i< n; i++)  
    {  
        wt[i] = proc[i - 1].burst_time + wt[i - 1];  
    }  
}  

void find_turnaround_time(struct process proc[], int n, int wt[], int tat[])  
{  
    int i;  
    for(i = 0; i< n; i++)  
    {  
        tat[i] = proc[i].burst_time + wt[i];  
    }  
}  

void find_average_time(struct process proc[], int n)  
{  
    int wt[10], tat[10], total_wt = 0, total_tat = 0, i;  

    find_waiting_time(proc, n, wt);  
    find_turnaround_time(proc, n, wt, tat);  

    printf("\nProcess ID\tBurst Time\tPriority\tWaiting Time\tTurnaround Time");  

    for(i = 0; i< n; i++)  
    {  
        total_wt = total_wt + wt[i];  
        total_tat = total_tat + tat[i];  
        printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d", proc[i].process_id, proc[i].burst_time, proc[i].priority, wt[i], tat[i]);  
    }  

    printf("\n\nAverage Waiting Time = %f", (float)total_wt/n);  // Fixed typo here
    printf("\nAverage Turnaround Time = %f\n", (float)total_tat/n);  
}  

void priority_scheduling(struct process proc[], int n)  
{  
    int i, j, pos;  
    struct process temp;  
    for(i = 0; i< n; i++)  
    {  
        pos = i;  
        for(j = i + 1; j < n; j++)  
        {  
            if(proc[j].priority < proc[pos].priority)  
                pos = j;  
        }  

        temp = proc[i];  
        proc[i] = proc[pos];  
        proc[pos] = temp;  
    }  

    find_average_time(proc, n);  
}

Output:

Enter the number of processes: 2

Enter the process ID: 1
Enter the burst time: 1
Enter the priority: 3

Enter the process ID: 2
Enter the burst time: 2
Enter the priority: 1

Process ID	Burst Time	Priority	Waiting Time	Turnaround Time
2		2		1		0		2
1		1		3		2		3

Average Waiting Time = 1.000000
Average Turnaround Time = 2.500000


=== Code Execution Successful ===

Advantages and Disadvantages of Priority Scheduling Algorithm

Advantages:

  • Priority scheduling ensures high priority processes are executed first. Therefore it has quicker completion of time-sensitive or critical tasks.
  • It is particularly useful for real-time systems that need to meet strict timing constraints.
  • Processes that require more CPU time can have their priority increased. So, it speeds up overall execution.

Disadvantages: 

  • Priority inversion occurs when a lower priority process holds a resource needed by a higher priority process. This can cause delays in the execution of critical tasks.
  • If the system is overwhelmed with high priority processes lower priority processes may never get a chance to execute. This can lead to starvation.
  • Techniques to avoid priority inversions, like priority inheritance or priority ceiling protocols, add complexity to the system.
  • Setting and managing priorities effectively can be difficult. This is especially when dealing with many processes with varying priority levels.

Conclusion

Understanding priority scheduling is essential for both students and professionals entering the world of coding. It’s a key concept in managing system resources efficiently, especially when dealing with multiple processes. It prepares you to tackle complex system design problems and enhances your problem-solving capabilities in programming. To learn more and build professional skills, enroll into the CCBP 4.0 Academy certification program. 

Frequently Asked Questions

1. What is priority scheduling in operating systems?

Priority scheduling is a CPU scheduling algorithm where processes are assigned priorities. The CPU executes them based on the highest priority first.

2. What are the two types of priority scheduling?

The two types are preemptive and non-premptive. In the first one higher priority processes can interrupt lower priority ones. In non-preemptive  once a process starts, it runs to completion.

3. How does priority scheduling help real-time systems?

Priority scheduling ensures that critical tasks in real-time systems are executed first. It meets strict timing constraints and deadlines.

4. What is priority inversion?

Priority inversion happens when a lower-priority process holds a resource needed by a higher-priority process. This causing delays in execution.

5. How can starvation be prevented in priority scheduling?

Starvation can be prevented by using techniques like ageing. In this way, the priority of waiting processes gradually increases over time.

Read More Articles

Chat with us
Chat with us
Talk to career expert