First Come First Serve (FCFS) Scheduling Algorithm in OS with Examples and Programs

FCFS scheduling algorithm is implemented in OS that helps to manage the execution of tasks and processes in a queue. So, now we are going to explain about First Come First Serve (FCFS) scheduling with their examples and suitable programs in (C, C++, C#, Java, and Python) with ease. This is unique article over the internet; so at the end of this post; you will definitely educate about FCFS Scheduling in OS without getting any hassle.

What is FCFS Scheduling in OS?

FCFS (First-Come, First-Served) is a scheduling algorithm used in operating systems to manage the execution of processes or tasks in a queue. In this algorithm, the process that arrives first is executed first, and the next process in the queue can only start after the first process completes its execution.

FCFS-scheduling

The FCFS scheduling algorithm is easy to implement, and it ensures fairness by executing the processes in the order in which they arrive. However, it may not be the best algorithm in terms of overall system performance, as it can lead to long waiting times for processes that arrive later, especially if the first process is long-running.

In FCFS scheduling, the ready queue maintains a sequence of all the processes that are ready to execute. When a new process arrives, it is added to the end of the queue, and the CPU executes the process at the front of the queue. Once the process completes its execution, it is removed from the queue, and the next process in the queue is executed. The scheduler continuously checks the ready queue to see if any new processes have arrived and adds them to the end of the queue.

FCFS 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 FCFS Scheduling in OS?
  • Pre-Emptive Approach in FCFS Scheduling
  • Non Pre-Emptive Approach in FCFS Scheduling
  1. How FCFS Scheduling Algorithm Works?
  2. How to Calculate Average Waiting Time in FCFS Scheduling?
  3. What is the Real-Life Example of FCFS Scheduling?
  • Convoy Effect in FCFS Scheduling
  1. What are the Advantages and Disadvantages of FCFS Scheduling?
  2. Characteristics of FCFS Scheduling
  • First Come First Serve Algorithm Program in C
  • First Come First Serve Algorithm Program in C++
  • First Come First Serve Algorithm Program in C#
  • First Come First Serve Algorithm Program in Java
  • FCFS Scheduling Program in Python

Let’s Get Started!!

The FCFS scheduling algorithm is suitable for systems where the processes have similar characteristics and the arrival rate is relatively low. It may not be the best choice for systems with high variability in process execution time and arrival rate, where other scheduling algorithms like Round Robin or Shortest Job First may be more appropriate.

Pre-Emptive Approach in FCFS Scheduling

First-Come-First-Serve (FCFS) scheduling is a non preemptive scheduling algorithm in which the process that arrives first is served first. In this algorithm, once a process starts executing, it is not interrupted until it completes or requests for an I/O operation. Therefore, there is no preemption in the FCFS scheduling algorithm.

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

However, it is possible to implement a pre-emptive approach in FCFS scheduling by using a priority queue. In this approach, each process is assigned a priority based on some criteria such as its arrival time or the amount of CPU time it has already used. The process with the highest priority is selected for execution, and if a new process with a higher priority arrives, it preempts the currently running process.

To implement this approach, the processes are first sorted based on their arrival time. Then, a priority queue is used to store the processes in the order of their priority. When a process arrives, it is added to the priority queue. If the queue is empty, the process is executed. If not, the process with the highest priority is selected for execution. If a new process arrives with a higher priority, it preempts the currently running process, and the newly arrived process is executed.

The pre-emptive approach in FCFS scheduling can be useful in situations where some processes have a higher priority than others, and it is important to ensure that these processes are executed as soon as possible. However, it can also lead to a situation where a low-priority process is continuously preempted by high-priority processes, leading to starvation. Therefore, the priorities assigned to the processes should be carefully chosen to avoid such situations.

Non Pre-Emptive Approach in FCFS Scheduling

In the First-Come-First-Serve (FCFS) scheduling algorithm, a non-preemptive approach means that once a process starts executing, it cannot be interrupted until it completes its execution or gets blocked. In other words, the CPU is allocated to the first process that arrives and starts executing, and it keeps executing until it finishes or blocks, even if a higher-priority process arrives in the meantime.

Non-preemptive scheduling is simple to implement and requires minimal overhead, but it may not always be the most efficient approach. Since the scheduler does not consider the priority of the arriving processes, it may lead to situations where low-priority processes have to wait a long time to be executed while high-priority processes are waiting in the queue. This can result in poor system performance, especially in real-time systems where certain tasks have strict deadlines to meet.

To address this issue, preemptive scheduling algorithms such as Shortest Remaining Time First (SRTF) or Round-Robin (RR) scheduling can be used. These algorithms allow the scheduler to interrupt a running process and switch to a higher-priority process when it arrives, thus ensuring that critical tasks are executed in a timely manner. However, preemptive scheduling algorithms are more complex to implement and may incur higher overhead compared to non-preemptive algorithms like FCFS.

How FCFS Scheduling Algorithm Works?

First-Come-First-Serve (FCFS) is a basic scheduling algorithm that processes tasks in the order in which they arrive in the ready queue. It is a non-preemptive scheduling algorithm, which means that once a process starts executing, it continues until it completes or blocks for I/O.

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

When a process enters the ready queue, it is assigned a CPU burst, which is the amount of time it needs to execute its code before it needs to perform I/O or wait for an event. The scheduler selects the first process from the ready queue and assigns it to the CPU for execution. The process executes until it either completes its CPU burst or blocks for I/O.

If the process completes its CPU burst, it is removed from the ready queue and its completion time is recorded. The next process in the ready queue is selected for execution, and the process continues until all processes have completed their CPU bursts.

If a process blocks for I/O, it is removed from the CPU and placed in the I/O queue. When the I/O operation is completed, the process is placed back in the ready queue, and the scheduler selects the next process for execution.

The FCFS scheduling algorithm is simple to implement and is fair because it processes tasks in the order they arrived. However, it can lead to long waiting times for processes with longer CPU bursts because they block the CPU while shorter tasks wait in the ready queue. Additionally, it may not be suitable for interactive systems because it does not allow for prioritization of important tasks.

How to Calculate Average Waiting Time in FCFS Scheduling?

The average waiting time in First-Come-First-Serve (FCFS) scheduling can be calculated using the following formula:

Average Waiting Time = (Total Waiting Time of All Processes) / (Number of Processes)

To calculate the total waiting time of all processes in FCFS scheduling, you need to first determine the waiting time of each process. The waiting time of a process is the amount of time it spends waiting in the ready queue before it starts executing.

To calculate the waiting time of a process, you can use the following formula:

Waiting Time = (Arrival Time of the Process) – (Arrival Time of the First Process in the Queue)

The arrival time of the first process in the queue is the same as the arrival time of the first process in the system. You can assume that the first process arrives at time 0.

Once you have calculated the waiting time of each process, you can add them up to get the total waiting time of all processes. Then, divide this total by the number of processes to get the average waiting time.

Here is an example to illustrate the calculation:

Assume that you have three processes with the following arrival times and burst times:

Process   Arrival Time    Burst Time

P1                   0                           5

P2                   1                           3

P3                   2                          6

First, you need to calculate the waiting time of each process using the formula mentioned above. For example, the waiting time of P1 is 0 (since it arrives at time 0 and is the first process in the queue), the waiting time of P2 is 4 (since it arrives at time 1 and has to wait for P1 to finish executing), and the waiting time of P3 is 6 (since it arrives at time 2 and has to wait for P1 and P2 to finish executing).

Next, you add up the waiting times of all processes to get the total waiting time:

Total Waiting Time = 0 + 4 + 6 = 10

Finally, you divide the total waiting time by the number of processes to get the average waiting time:

Average Waiting Time = 10 / 3 = 3.33 (rounded to two decimal places)

Therefore, the average waiting time for the three processes in FCFS scheduling is 3.33 time units.

What is the Real-Life Example of FCFS Scheduling?

One real-life example of FCFS algorithm can be seen in a fast-food restaurant where customers are served in the order they arrive.

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

For instance, imagine a fast-food restaurant where there is only one server to take orders and serve food. Customers arrive at the restaurant and place their orders one by one. The server processes each order in the order they were received, without any priority given to any customer. The first customer to arrive at the restaurant will be the first to have their order taken and served, followed by the second customer, the third, and so on.

This scenario follows the FCFS algorithm because the customer who arrives first gets served first. The algorithm works efficiently in such scenarios because there is only one resource (server) and it is available to serve the customers one at a time. However, in scenarios where there are multiple resources, or some tasks require higher priority than others, other scheduling algorithms may be more suitable.

Convoy Effect in FCFS Scheduling

The Convoy Effect is a phenomenon that can occur in First-Come-First-Serve (FCFS) scheduling algorithms, particularly in operating systems. It refers to a situation where a large process occupies a shared resource, such as a CPU, for an extended period of time, causing smaller processes to wait in a queue behind it. This can result in decreased overall system throughput and increased average waiting times for smaller processes.

In FCFS scheduling, processes are executed in the order in which they arrive in the ready queue, with the first process in the queue being the first to be executed. If a long-running process enters the queue before smaller processes, it will be executed first, which can cause other smaller processes to wait for a long time.

The Convoy Effect is a result of the FCFS scheduling policy, as it prioritizes the first process in the queue over all others, regardless of their size or priority level. To mitigate the impact of the Convoy Effect, other scheduling algorithms can be used, such as Shortest Job First (SJF) or Priority Scheduling, which take into account the size or priority level of processes in determining which process should be executed next.

In short, the Convoy Effect is a potential issue that can arise in FCFS scheduling algorithms, where a large process can cause smaller processes to wait for extended periods, reducing overall system throughput and increasing average waiting times. It can be mitigated by using other scheduling algorithms that take into account the size or priority level of processes.

What are the Advantages and Disadvantages of FCFS Scheduling?

In FCFS scheduling, the process that arrives first is executed first, followed by the next process in the queue, and so on. Here are some advantages and disadvantages of FCFS scheduling:

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

Advantages of FCFS Scheduling:

FCFS (First-Come, First-Serve) scheduling is a simple and commonly used CPU scheduling algorithm in operating systems. Its main advantage is its simplicity and fairness in scheduling processes. Here are some of the advantages of FCFS scheduling:

Easy to Understand and Implement: FCFS scheduling is easy to understand and implement compared to other complex scheduling algorithms.

Fairness: FCFS scheduling is a fair algorithm because it allocates CPU time based on the order in which processes arrive. The first process that arrives gets executed first, and the next process in the queue waits for its turn. This ensures that no process is given priority over others, and every process gets a chance to execute.

No Starvation: FCFS scheduling ensures that no process will be starved of CPU time, as every process will eventually get a turn to execute.

Low Overhead: FCFS scheduling has low overhead as it does not require any complex data structures or computations.

Simple to Calculate Waiting Time: FCFS scheduling is simple to calculate waiting time for each process, making it useful for teaching purposes.

Overall, FCFS scheduling is a simple and fair algorithm that is easy to implement and understand. It ensures that all processes get a chance to execute without any starvation and has low overhead.

Disadvantages of FCFS Scheduling:

FCFS (First-Come, First-Served) scheduling has some advantages, such as simplicity and easy implementation; it also has several disadvantages, including:

Poor Turnaround Time: In FCFS scheduling, processes that arrive first are executed first, regardless of their length. As a result, longer processes may have to wait a long time before they get executed, leading to poor turnaround time.

Convoy Effect: The convoy effect is a phenomenon in which a large, slow-moving process holds up several small, fast-moving processes, leading to increased waiting time and reduced throughput. FCFS scheduling is prone to the convoy effect since it executes processes in the order they arrive, regardless of their size.

Low Priority Processes May Starve: If a low-priority process arrives before a high-priority process, it will be executed first in FCFS scheduling, leading to a situation where high-priority processes may have to wait a long time before getting executed. This may result in low-priority processes running indefinitely and high-priority processes never getting executed.

Inefficient Use of Resources: FCFS scheduling may lead to inefficient use of resources since it does not take into account the current state of the system or the priority of the processes. This may lead to situations where resources are idle even when there are processes waiting for them.

Hence, FCFS scheduling is easy to implement and understand, it is not an optimal scheduling algorithm for many real-world situations. Other scheduling algorithms, such as Round Robin or Priority Scheduling, may be more suitable for specific use cases.

Characteristics of FCFS Scheduling

Here are some characteristics of FCFS scheduling, as follow them:

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

Non-Preemptive: FCFS is a non-preemptive scheduling algorithm, which means that once a process starts executing, it will continue to run until it completes or blocks for I/O.

Simple: FCFS is a simple and easy-to-understand scheduling algorithm. It does not require any complex calculations or heuristics to determine which process should be executed next.

Fairness: FCFS provides fairness to all processes by treating them in the order they arrive. The first process that arrives in the ready queue is the first to be executed, and so on.

Throughput: FCFS may not be the best algorithm in terms of throughput, as it may lead to a situation where a long-running process occupies the CPU, causing other shorter processes to wait in the ready queue.

Convoy Effect: FCFS is prone to the convoy effect, where a long-running process may be followed by several short processes, which must wait until the long process finishes. This can lead to a lot of idle time for the CPU.

Poor Response Time: FCFS can lead to poor response time for interactive processes, as they may have to wait for a long time before they get a chance to execute.

First Come First Serve Algorithm Program in C

Here’s an example program for First Come First Serve (FCFS) algorithm in C:

#include <stdio.h>

// Function to find the waiting time for all processes

void findWaitingTime(int n, int bt[], int wt[])

{

    // Waiting time for first process is 0

    wt[0] = 0;

    // Calculate waiting time for remaining processes

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

        wt[i] = wt[i-1] + bt[i-1];

}

// Function to find the turnaround time for all processes

void findTurnAroundTime(int n, int bt[], int wt[], int tat[])

{

    // Calculate turnaround time by adding bt[i] + wt[i]

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

        tat[i] = bt[i] + wt[i];

}

// Function to calculate average time

void findAvgTime(int n, int bt[])

{

    int wt[n], tat[n], total_wt = 0, total_tat = 0;

    // Find waiting time of all processes

    findWaitingTime(n, bt, wt);

    // Find turnaround time of all processes

    findTurnAroundTime(n, bt, wt, tat);

    // Display processes along with all details

    printf(“Processes  Burst time  Waiting time  Turn around time\n”);

    // Calculate total waiting time and total turnaround time

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

        total_wt = total_wt + wt[i];

        total_tat = total_tat + tat[i];

        printf(”   %d\t\t%d\t    %d\t\t  %d\n”, i+1, bt[i], wt[i], tat[i]);

    }

    // Calculate the average waiting time and average turnaround time

    printf(“\nAverage waiting time = %f”, (float)total_wt / (float)n);

    printf(“\nAverage turn around time = %f”, (float)total_tat / (float)n);

}

// Main function

int main()

{

    int n = 4;

    int burst_time[] = { 5, 8, 2, 6 };

    findAvgTime(n, burst_time);

    return 0;

}

This program finds the waiting time and turnaround time for a set of processes using the FCFS scheduling algorithm. It takes the number of processes and an array of burst times for each process as input. The output is the average waiting time and average turnaround time for all the processes.

First Come First Serve Algorithm Program in C++

Here’s an example program for First Come First Serve (FCFS) algorithm in C++:

#include <iostream>

#include <queue>

using namespace std;

// Function to find the waiting time for all processes

void findWaitingTime(int processes[], int n, int bt[], int wt[])

{

    // Waiting time for first process is 0

    wt[0] = 0;

    // Calculate waiting time for remaining processes

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

        wt[i] = wt[i-1] + bt[i-1];

}

// Function to find the turnaround time for all processes

void findTurnAroundTime(int processes[], int n, int bt[], int wt[], int tat[])

{

    // Calculate turnaround time by adding bt[i] + wt[i]

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

        tat[i] = bt[i] + wt[i];

}

// Function to calculate average time

void findAvgTime(int processes[], int n, int bt[])

{

    int wt[n], tat[n], total_wt = 0, total_tat = 0;

    // Find waiting time of all processes

    findWaitingTime(processes, n, bt, wt);

    // Find turnaround time of all processes

    findTurnAroundTime(processes, n, bt, wt, tat);

    // Display processes along with all details

    cout << “Processes  Burst time  Waiting time  Turn around time\n”;

    // Calculate total waiting time and total turnaround time

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

        total_wt = total_wt + wt[i];

        total_tat = total_tat + tat[i];

        cout << ”   ” << processes[i] << “\t\t” << bt[i] << “\t    “

             << wt[i] << “\t\t  ” << tat[i] << endl;

    }

    // Calculate the average waiting time and average turnaround time

    cout << “\nAverage waiting time = ” << (float)total_wt / (float)n;

    cout << “\nAverage turn around time = ” << (float)total_tat / (float)n;

}

// Main function

int main()

{

    int processes[] = { 1, 2, 3, 4 };

    int n = sizeof processes / sizeof processes[0];

    // Burst time of all processes

    int burst_time[] = { 5, 8, 2, 6 };

    findAvgTime(processes, n, burst_time);

    return 0;

}

This program finds the waiting time and turnaround time for a set of processes using the FCFS scheduling algorithm. It takes an array of process IDs, an array of burst times for each process, and the number of processes as input. The output is the average waiting time and average turnaround time for all the processes.

First Come First Serve Algorithm Program in C#

Sure, here is a basic implementation of the First Come First Serve (FCFS) algorithm in C#:

using System;

class FCFS

{

    static void Main(string[] args)

    {

        int[] burstTime = { 10, 5, 8, 3 }; // Burst time of the processes

        int n = burstTime.Length;

        int[] waitingTime = new int[n]; // Waiting time of the processes

        int[] turnaroundTime = new int[n]; // Turnaround time of the processes

        waitingTime[0] = 0; // The first process doesn’t have to wait

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

        {

            waitingTime[i] = waitingTime[i – 1] + burstTime[i – 1]; // Calculate the waiting time of the current process

        }

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

        {

            turnaroundTime[i] = waitingTime[i] + burstTime[i]; // Calculate the turnaround time of each process

        }

        Console.WriteLine(“Process\tBurst Time\tWaiting Time\tTurnaround Time”);

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

        {

            Console.WriteLine(“{0}\t{1}\t\t{2}\t\t{3}”, i + 1, burstTime[i], waitingTime[i], turnaroundTime[i]); // Display the results

        }

        Console.ReadKey();

    }

}

In this example, the burst time of the processes is given in the burstTime array, and the number of processes is determined by the length of the array. The waiting time and turnaround time of each process are calculated using the FCFS algorithm, and then displayed in a table.

Note that this is just a basic example, and in a real-world scenario you would need to handle more complex situations such as preemption and process priorities.

First Come First Serve Algorithm Program in Java

Here’s a Java program for the First Come First Serve (FCFS) scheduling algorithm:

import java.util.Scanner;

public class FCFS {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

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

        int n = sc.nextInt();

        int[] arrivalTime = new int[n];

        int[] burstTime = new int[n];

        int[] completionTime = new int[n];

        int[] waitingTime = new int[n];

        int[] turnaroundTime = new int[n];

        System.out.println(“\nEnter the arrival time and burst time for each process:”);

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

            System.out.print(“Arrival time of process “+(i+1)+”: “);

            arrivalTime[i] = sc.nextInt();

            System.out.print(“Burst time of process “+(i+1)+”: “);

            burstTime[i] = sc.nextInt();

        }

        // Calculate completion time of each process

        completionTime[0] = arrivalTime[0] + burstTime[0];

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

            completionTime[i] = completionTime[i-1] + burstTime[i];

        }

        // Calculate waiting time of each process

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

            waitingTime[i] = completionTime[i] – burstTime[i] – arrivalTime[i];

        }

        // Calculate turnaround time of each process

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

            turnaroundTime[i] = completionTime[i] – arrivalTime[i];

        }

        // Calculate average waiting time and average turnaround time

        double avgWaitingTime = 0;

        double avgTurnaroundTime = 0;

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

            avgWaitingTime += waitingTime[i];

            avgTurnaroundTime += turnaroundTime[i];

        }

        avgWaitingTime /= n;

        avgTurnaroundTime /= n;

        // Display results

        System.out.println(“\nProcess\tArrival Time\tBurst Time\tCompletion Time\tWaiting Time\tTurnaround Time”);

        for(int i=0; i<n; i++){         System.out.println((i+1)+”\t”+arrivalTime[i]+”\t\t”+burstTime[i]+”\t\t”+completionTime[i]+”\t\t”+waitingTime[i]+”\t\t”+turnaroundTime[i]);

        }

        System.out.println(“\nAverage Waiting Time: “+avgWaitingTime);

        System.out.println(“Average Turnaround Time: “+avgTurnaroundTime);

        sc.close();

    }

}

In this program, the user is prompted to enter the number of processes and the arrival time and burst time for each process. The completion time, waiting time, and turnaround time are then calculated for each process using the FCFS scheduling algorithm. Finally, the results are displayed, including the average waiting time and average turnaround time.

FCFS Scheduling Program in Python

Sure! Here’s an implementation of First Come First Serve (FCFS) scheduling algorithm in Python:

class Process:

    def __init__(self, pid, arrival_time, burst_time):

        self.pid = pid

        self.arrival_time = arrival_time

        self.burst_time = burst_time

def fcfs_scheduling(processes):

    “””

    This function takes a list of Process objects as input and returns the average waiting time

    and turnaround time using First Come First Serve (FCFS) scheduling algorithm.

    “””

    n = len(processes)

    waiting_time = [0] * n

    turnaround_time = [0] * n

    # Sort the processes based on their arrival time

    processes.sort(key=lambda x: x.arrival_time)

    # Calculate waiting time and turnaround time for each process

    for i in range(n):

        if i == 0:

            waiting_time[i] = 0

        else:

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

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

    # Calculate the average waiting time and turnaround time

    avg_waiting_time = sum(waiting_time) / n

    avg_turnaround_time = sum(turnaround_time) / n

    return avg_waiting_time, avg_turnaround_time

To use this function, you can create a list of Process objects, where each object represents a process with its process ID (pid), arrival time (arrival_time), and burst time (burst_time). For example:

processes = [

    Process(1, 0, 5),

    Process(2, 1, 3),

    Process(3, 2, 8),

    Process(4, 3, 6),

    Process(5, 4, 1),

]

avg_waiting_time, avg_turnaround_time = fcfs_scheduling(processes)

print(“Average Waiting Time:”, avg_waiting_time)

print(“Average Turnaround Time:”, avg_turnaround_time)

This will output:

Average Waiting Time: 5.2

Average Turnaround Time: 10.2

We hope this helps! Let me know if you have any questions.

The Bottom Words

Now, we make ensure that you have been fully understood about First Come First Serve (FCFS) scheduling with their examples and suitable programs in (C, C++, C#, Java, and Python) with ease. If this article is useful 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: Page Fault in OS (Operating System) | Page Fault Handling in OS!!

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

Happy Learning!!

0 Comments

  1. What refreshing delight your posts are. I understood this should be here yet I ultimately became fortunate and the search terms worked. Getting more people to be part of the discussion is actually a positive thing.

Leave a Reply

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