The Wayback Machine - https://web.archive.org/web/20240910013430/https://www.geeksforgeeks.org/program-for-fcfs-cpu-scheduling-set-1/
Open In App

Program for FCFS CPU Scheduling | Set 1

Last Updated : 01 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. 

Terminologies Used in CPU Scheduling 

  • Arrival Time: The time at which the process arrives in the ready queue.
  • Completion Time: The time at which the process completes its execution.
  • Turn Around Time: Time Difference between completion time and arrival time. Turn Around Time = (Completion Time – Arrival Time)
  • Waiting Time (W. T): Time Difference between turnaround time and burst time Ie.
  • Waiting Time = (Turn Around Time – Burst Time).

In this example, we have assumed the arrival time of all processes is 0, so turnaround and completion times are the same. 

Implementation

1 - Input the processes along with their burst time (bt).
2 - Find waiting time (wt) for all processes.
3 - As first process that comes need not to wait so 
    waiting time for process 1 will be 0 i.e. wt[0] = 0.
4 - Find waiting time for all other processes i.e. for
     process i -> 
       wt[i] = bt[i-1] + wt[i-1] .
5 - Find turnaround time = waiting_time + burst_time 
    for all processes.
6 - Find average waiting time = 
                 total_waiting_time / no_of_processes.
7 - Similarly, find average turnaround time = 
                 total_turn_around_time / no_of_processes.

Code to Implement the Algorithm

C++
// C++ program for implementation of FCFS 
// scheduling
#include<iostream>
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;

    // calculating waiting time
    for (int  i = 1; i < n ; i++ )
        wt[i] =  bt[i-1] + wt[i-1] ;
}

// Function to calculate turn around time
void findTurnAroundTime( int processes[], int n, 
                  int bt[], int wt[], int tat[])
{
    // calculating 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;

    //Function to find waiting time of all processes
    findWaitingTime(processes, n, bt, wt);

    //Function to find turn around time for 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 turn 
    // around time
    for (int  i=0; i<n; i++)
    {
        total_wt = total_wt + wt[i];
        total_tat = total_tat + tat[i];
        cout << "   " << i+1 << "\t\t" << bt[i] <<"\t    "
            << wt[i] <<"\t\t  " << tat[i] <<endl;
    }

    cout << "Average waiting time = " 
         << (float)total_wt / (float)n;
    cout << "\nAverage turn around time = " 
         << (float)total_tat / (float)n;
}

// Driver code
int main()
{
    //process id's
    int processes[] = { 1, 2, 3};
    int n = sizeof processes / sizeof processes[0];

    //Burst time of all processes
    int  burst_time[] = {10, 5, 8};

    findavgTime(processes, n,  burst_time);
    return 0;
}
C
// C program for implementation of FCFS  
// scheduling 
#include<stdio.h> 
// 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; 
  
    // calculating waiting time 
    for (int  i = 1; i < n ; i++ ) 
        wt[i] =  bt[i-1] + wt[i-1] ; 
} 
  
// Function to calculate turn around time 
void findTurnAroundTime( int processes[], int n,  
                  int bt[], int wt[], int tat[]) 
{ 
    // calculating 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; 
  
    //Function to find waiting time of all processes 
    findWaitingTime(processes, n, bt, wt); 
  
    //Function to find turn around time for all processes 
    findTurnAroundTime(processes, 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 turn  
    // around time 
    for (int  i=0; i<n; i++) 
    { 
        total_wt = total_wt + wt[i]; 
        total_tat = total_tat + tat[i]; 
        printf("   %d ",(i+1));
        printf("       %d ", bt[i] );
        printf("       %d",wt[i] );
        printf("       %d\n",tat[i] ); 
    } 
    float s=(float)total_wt / (float)n;
    float t=(float)total_tat / (float)n;
    printf("Average waiting time = %f",s);
    printf("\n");
    printf("Average turn around time = %f ",t); 
} 
  
// Driver code 
int main() 
{ 
    //process id's 
    int processes[] = { 1, 2, 3}; 
    int n = sizeof processes / sizeof processes[0]; 
  
    //Burst time of all processes 
    int  burst_time[] = {10, 5, 8}; 
  
    findavgTime(processes, n,  burst_time); 
    return 0; 
} 
// This code is contributed by Shivi_Aggarwal
Java
// Java program for implementation of FCFS 
// scheduling 

import java.text.ParseException;

class GFG {

    // Function to find the waiting time for all 
    // processes 
    static void findWaitingTime(int processes[], int n,
            int bt[], int wt[]) {
        // waiting time for first process is 0 
        wt[0] = 0;

        // calculating waiting time 
        for (int i = 1; i < n; i++) {
            wt[i] = bt[i - 1] + wt[i - 1];
        }
    }

    // Function to calculate turn around time 
    static void findTurnAroundTime(int processes[], int n,
            int bt[], int wt[], int tat[]) {
        // calculating 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 
    static void findavgTime(int processes[], int n, int bt[]) {
        int wt[] = new int[n], tat[] = new int[n];
        int total_wt = 0, total_tat = 0;

        //Function to find waiting time of all processes 
        findWaitingTime(processes, n, bt, wt);

        //Function to find turn around time for all processes 
        findTurnAroundTime(processes, n, bt, wt, tat);

        //Display processes along with all details 
        System.out.printf("Processes 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.printf(" %d ", (i + 1));
            System.out.printf("     %d ", bt[i]);
            System.out.printf("     %d", wt[i]);
            System.out.printf("     %d\n", tat[i]);
        }
        float s = (float)total_wt /(float) n;
        int t = total_tat / n;
        System.out.printf("Average waiting time = %f", s);
        System.out.printf("\n");
        System.out.printf("Average turn around time = %d ", t);
    }

    // Driver code 
    public static void main(String[] args) throws ParseException {
        //process id's 
        int processes[] = {1, 2, 3};
        int n = processes.length;

        //Burst time of all processes 
        int burst_time[] = {10, 5, 8};

        findavgTime(processes, n, burst_time);

    }
}
// This code is contributed by 29ajaykumar 
Python
# Python3 program for implementation 
# of FCFS scheduling

# Function to find the waiting 
# time for all processes
def findWaitingTime(processes, n,
                    bt, wt):

    # waiting time for 
    # first process is 0
    wt[0] = 0

    # calculating waiting time
    for i in range(1, n ):
        wt[i] = bt[i - 1] + wt[i - 1] 

# Function to calculate turn
# around time
def findTurnAroundTime(processes, n, 
                       bt, wt, tat):

    # calculating turnaround 
    # time by adding bt[i] + wt[i]
    for i in range(n):
        tat[i] = bt[i] + wt[i]

# Function to calculate
# average time
def findavgTime( processes, n, bt):

    wt = [0] * n
    tat = [0] * n 
    total_wt = 0
    total_tat = 0

    # Function to find waiting 
    # time of all processes
    findWaitingTime(processes, n, bt, wt)

    # Function to find turn around 
    # time for all processes
    findTurnAroundTime(processes, n, 
                       bt, wt, tat)

    # Display processes along
    # with all details
    print( "Processes Burst time " + 
                  " Waiting time " + 
                " Turn around time")

    # Calculate total waiting time 
    # and total turn around time
    for i in range(n):
    
        total_wt = total_wt + wt[i]
        total_tat = total_tat + tat[i]
        print(" " + str(i + 1) + "\t\t" + 
                    str(bt[i]) + "\t " + 
                    str(wt[i]) + "\t\t " + 
                    str(tat[i])) 

    print( "Average waiting time = "+
                   str(total_wt / n))
    print("Average turn around time = "+
                     str(total_tat / n))

# Driver code
if __name__ =="__main__":
    
    # process id's
    processes = [ 1, 2, 3]
    n = len(processes)

    # Burst time of all processes
    burst_time = [10, 5, 8]

    findavgTime(processes, n, burst_time)

# This code is contributed 
# by ChitraNayal
C#
// C# program for implementation of FCFS 
// scheduling 
using System;
    
class GFG 
{

    // Function to find the waiting time for all 
    // processes 
    static void findWaitingTime(int []processes, int n,
                                int []bt, int[] wt) 
    {
        // waiting time for first process is 0 
        wt[0] = 0;

        // calculating waiting time 
        for (int i = 1; i < n; i++) 
        {
            wt[i] = bt[i - 1] + wt[i - 1];
        }
    }

    // Function to calculate turn around time 
    static void findTurnAroundTime(int []processes, int n,
            int []bt, int []wt, int []tat) {
        // calculating 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 
    static void findavgTime(int []processes, int n, int []bt)
    {
        int []wt = new int[n];
        int []tat = new int[n];
        int total_wt = 0, total_tat = 0;

        //Function to find waiting time of all processes 
        findWaitingTime(processes, n, bt, wt);

        //Function to find turn around time for all processes 
        findTurnAroundTime(processes, n, bt, wt, tat);

        //Display processes along with all details 
        Console.Write("Processes 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];
            Console.Write(" {0} ", (i + 1));
            Console.Write("     {0} ", bt[i]);
            Console.Write("     {0}", wt[i]);
            Console.Write("     {0}\n", tat[i]);
        }
        float s = (float)total_wt /(float) n;
        int t = total_tat / n;
        Console.Write("Average waiting time = {0}", s);
        Console.Write("\n");
        Console.Write("Average turn around time = {0} ", t);
    }

    // Driver code 
    public static void Main(String[] args)
    {
        // process id's 
        int []processes = {1, 2, 3};
        int n = processes.Length;

        // Burst time of all processes 
        int []burst_time = {10, 5, 8};

        findavgTime(processes, n, burst_time);
    }
}

// This code contributed by Rajput-Ji
JavaScript
<script>

    // JavaScript program for implementation of FCFS 
   // scheduling
   
   
   // Function to find the waiting time for all 
  // processes
    function findWaitingTime(processes,n,bt,wt)
    {
        // waiting time for first process is 0 
        wt[0] = 0;
  
        // calculating waiting time 
        for (let i = 1; i < n; i++) {
            wt[i] = bt[i - 1] + wt[i - 1];
        }
    }
    
    function findTurnAroundTime(processes,n,bt,wt,tat)
    {
        // calculating turnaround time by adding 
        // bt[i] + wt[i] 
        for (let i = 0; i < n; i++) {
            tat[i] = bt[i] + wt[i];
        }
    }
    
    function findavgTime(processes,n,bt)
    {
        let wt = new Array(n), tat = new Array(n);
        for(let i=0;i<n;i++)
        {
            wt[i]=0;
            tat[i]=0;
        }
        let total_wt = 0, total_tat = 0;
  
        //Function to find waiting time of all processes 
        findWaitingTime(processes, n, bt, wt);
  
        //Function to find turn around time for all processes 
        findTurnAroundTime(processes, n, bt, wt, tat);
  
        //Display processes along with all details 
        document.write("Processes Burst time Waiting"
                       +" time Turn around time<br>");
  
        // 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];
            document.write("    ", (i + 1)+" ");
            document.write("     "+  bt[i]+" ");
            document.write("     "+ wt[i]);
            document.write("     "+ tat[i]+"<br>");
        }
        let s = total_wt / n;
        let t = Math.floor(total_tat / n);
        document.write("Average waiting time = "+ s);
        document.write("<br>");
        document.write("Average turn around time = ", t+" ");
    }
    
    let processes=[1,2,3];
    let  n = processes.length;
    
    let burst_time=[10,5,8];
    findavgTime(processes, n, burst_time);
    
    // This code is contributed by rag2127
    
</script> 

Output: 

Processes  Burst time  Waiting time  Turn around time    //The Output is Wrong please correct it
 1        10     0         10
 2        5     10         15
 3        8     15         23
Average waiting time = 8.33333
Average turn around time = 16

Implementation Using OOPS

C++
#include <bits/stdc++.h>
using namespace std;

class Process {
private:
    int at;
    int bt;
    int ct;
    int tat;
    int wt;
    int pid;

public:
    int& operator[](string var)
    {
        if (var == "at")
            return at;
        if (var == "bt")
            return bt;
        if (var == "ct")
            return ct;
        if (var == "tat")
            return tat;
        if (var == "wt")
            return wt;
        return pid;
    }

    void update_after_ct()
    {
        tat = ct - at;
        wt = tat - bt;
    }

    void display()
    {
        printf("%d\t%d\t%d\t%d\t%d\t%d\n", pid, at, bt, ct,
               tat, wt);
    }
};

float average(vector<Process> P, string var)
{
    int total = 0;
    for (auto temp : P) {
        total += temp[var];
    }
    return (float)total / P.size();
}

int main()
{
    /*
    Input description.
    First line contains an integer n
    the next n lines contains 2 space separated integers
    containing values for arrival time and burst time for
    example:
    2
    0 3
    1 2
    */
    int n;
    cin >> n;
    int counter = 0;
    vector<Process> P(n);
    for (Process& temp : P) {
        temp["id"] = counter++;
        cin >> temp["at"] >> temp["bt"];
    }
    sort(P.begin(), P.end(),
         [](Process first, Process second) {
             return first["at"] < second["at"];
         });
    printf("pid\tat\tbt\tct\ttat\twt\n");
    P[0]["ct"] = P[0]["at"] + P[0]["bt"];
    P[0].update_after_ct();
    P[0].display();
    for (int i = 1; i < P.size(); i++) {
        if (P[i]["at"] < P[i - 1]["ct"]) {
            P[i]["ct"] = P[i - 1]["ct"] + P[i]["bt"];
        }
        else {
            printf("curr['at'] : %d, prev['ct'] : %d\n",
                   P[i]["at"], P[i - 1]["ct"]);
            P[i]["ct"] = P[i]["at"] + P[i]["bt"];
        }
        P[i].update_after_ct();
        P[i].display();
    }

    printf("Average waiting time : %f\n", average(P, "wt"));
    return 0;
}
Java
import java.util.*;

public class Main {
    
    // Process class to represent a process
    static class Process {
        private int at; // arrival time
        private int bt; // burst time
        private int ct; // completion time
        private int tat; // turn around time
        private int wt; // waiting time
        private int pid; // process ID

        // Getter method to get a variable value of the process
        public int getVar(String var) {
            if (var.equals("at"))
                return at;
            if (var.equals("bt"))
                return bt;
            if (var.equals("ct"))
                return ct;
            if (var.equals("tat"))
                return tat;
            if (var.equals("wt"))
                return wt;
            return pid;
        }

        // Setter method to set a variable value of the process
        public void setVar(String var, int value) {
            if (var.equals("at"))
                at = value;
            else if (var.equals("bt"))
                bt = value;
            else if (var.equals("ct"))
                ct = value;
            else if (var.equals("tat"))
                tat = value;
            else if (var.equals("wt"))
                wt = value;
            else
                pid = value;
        }

        // Update the turn around time and waiting time after completion
        public void updateAfterCt() {
            tat = ct - at;
            wt = tat - bt;
        }

        // Display the process details
        public void display() {
            System.out.printf("%d\t%d\t%d\t%d\t%d\t%d\n", pid, at, bt, ct, tat, wt);
        }
    }
    
    // Calculate the average of a variable value for all processes
    public static float average(ArrayList<Process> P, String var) {
        int total = 0;
        for (Process temp : P) {
            total += temp.getVar(var);
        }
        return (float) total / P.size();
    }
    
    public static void main(String[] args) {
        /*
        Input description.
        First line contains an integer n
        the next n lines contains 2 space separated integers
        containing values for arrival time and burst time for
        example:
        2
        0 3
        1 2
        */
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int counter = 0;
        ArrayList<Process> P = new ArrayList<Process>(n);
        // Create a process object for each input and add to the process list
        for (int i = 0; i < n; i++) {
            Process temp = new Process();
            temp.setVar("pid", counter++);
            temp.setVar("at", sc.nextInt());
            temp.setVar("bt", sc.nextInt());
            P.add(temp);
        }
        // Sort the process list by arrival time
        Collections.sort(P, new Comparator<Process>() {
            public int compare(Process first, Process second) {
                return first.getVar("at") - second.getVar("at");
            }
        });
        System.out.println("pid\tat\tbt\tct\ttat\twt");
        // Calculate completion time and display the details of the first process
        P.get(0).setVar("ct", P.get(0).getVar("at") + P.get(0).getVar("bt"));
        P.get(0).updateAfterCt();
        P.get(0).display();
        // Calculate completion time and display the details of the remaining processes
       for (int i = 1; i < P.size(); i++) {
           // Loop through the remaining processes
        if (P.get(i).getVar("at") < P.get(i - 1).getVar("ct")) {
            // If the process arrives before the previous process completes
            P.get(i).setVar("ct", P.get(i - 1).getVar("ct") + P.get(i).getVar("bt"));
            // Calculate completion time as the completion time of previous process plus its burst time
        } else {
            // If the process arrives after the previous process completes
            System.out.printf("curr['at'] : %d, prev['ct'] : %d\n\n", P.get(i).getVar("at"),
                    P.get(i - 1).getVar("ct"));
            P.get(i).setVar("ct", P.get(i).getVar("at") + P.get(i).getVar("bt"));
            // Calculate completion time as the arrival time plus its burst time
        }
        P.get(i).updateAfterCt(); // Update the turnaround time and waiting time for the current process
        P.get(i).display(); // Display the details of the current process
    }

    System.out.printf("Average waiting time : %f\n", average(P, "wt"));
    sc.close(); // Close the scanner
}
}
Python
class processes:
    def __init__(self, id, at, bt, ct):
        self.id = id
        self.at = at
        self.bt = bt
        self.ct = ct
        self.tat = self.ct-self.at
        self.wt = self.tat-self.bt

    def get(self):
        print(f"{self.id}\t{self.at}\t{self.bt}\t{self.ct}\t{self.tat}\t{self.wt}")

    def turnaround(self):
        return self.tat

    def waiting(self):
        return self.wt


num = int(input("Enter the Number of Processes:"))
l = []
ct = 0

for i in range(num):

    print(f'Process {i+1}')
    at = int(input("Enter the Arrival Time:-"))
    bt = int(input("Enter the Burst Time:-"))
    if (len(l) == 0):
        ct = bt
        l.append(processes(i, at, bt, ct))
    else:
        ct += bt
        l.append(processes(i, at, bt, ct))

    print("\n")
avg_tat = 0
avg_wat = 0
print("PID\tAT\tBT\tCT\tTAT\tWT")
for process in l:
    process.get()

for process in l:
    avg_tat += process.turnaround()
    avg_wat += process.waiting()
print(f"Avg_turnaround:{avg_tat/num}\nAvg_Waitingtime:{avg_wat/num}")

# pid at bt
# 0 0 5
# 1 2 3
# 2 6 2
# 3 7 3
C#
using System;
using System.Collections.Generic;

class Process
{
    private int at;
    private int bt;
    private int ct;
    private int tat;
    private int wt;
    private int pid;

    public int this[string var]
    {
        get
        {
            if (var == "at")
                return at;
            if (var == "bt")
                return bt;
            if (var == "ct")
                return ct;
            if (var == "tat")
                return tat;
            if (var == "wt")
                return wt;
            return pid;
        }
        set
        {
            if (var == "at")
                at = value;
            else if (var == "bt")
                bt = value;
            else if (var == "ct")
                ct = value;
            else if (var == "tat")
                tat = value;
            else if (var == "wt")
                wt = value;
            else
                pid = value;
        }
    }

    public void UpdateAfterCt()
    {
        tat = ct - at;
        wt = tat - bt;
    }

    public void Display()
    {
        Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}",
            pid, at, bt, ct, tat, wt);
    }
}

class Program
{
    static float Average(List<Process> P, string var)
    {
        int total = 0;
        foreach (var temp in P)
        {
            total += temp[var];
        }
        return (float)total / P.Count;
    }

    static void Main()
    {
        /*
        Input description.
        First line contains an integer n
        the next n lines contains 2 space separated integers
        containing values for arrival time and burst time for
        example:
        2
        0 3
        1 2
        */
        int n = int.Parse(Console.ReadLine());
        int counter = 0;
        var P = new List<Process>(n);
        for (int i = 0; i < n; i++)
        {
            var temp = new Process();
            temp["id"] = counter++;
            var line = Console.ReadLine().Split();
            temp["at"] = int.Parse(line[0]);
            temp["bt"] = int.Parse(line[1]);
            P.Add(temp);
        }
        P.Sort((first, second) => first["at"].CompareTo(second["at"]));
        Console.WriteLine("pid\tat\tbt\tct\ttat\twt");
        P[0]["ct"] = P[0]["at"] + P[0]["bt"];
        P[0].UpdateAfterCt();
        P[0].Display();
        for (int i = 1; i < P.Count; i++)
        {
            if (P[i]["at"] < P[i - 1]["ct"])
            {
                P[i]["ct"] = P[i - 1]["ct"] + P[i]["bt"];
            }
            else
            {
                Console.WriteLine("curr['at'] : {0}, prev['ct'] : {1}",
                    P[i]["at"], P[i - 1]["ct"]);
                P[i]["ct"] = P[i]["at"] + P[i]["bt"];
            }
            P[i].UpdateAfterCt();
            P[i].Display();
        }
        Console.WriteLine("Average waiting time : {0}", Average(P, "wt"));
    }
}
JavaScript
class Process {
  constructor() {
    this.at = 0;
    this.bt = 0;
    this.ct = 0;
    this.tat = 0;
    this.wt = 0;
    this.pid = 0;
  }

  update_after_ct() {
    this.tat = this.ct - this.at;
    this.wt = this.tat - this.bt;
  }

  display() {
    console.log(`${this.pid}\t${this.at}\t${this.bt}\t${this.ct}\t${this.tat}\t${this.wt}`);
  }
}

function average(P, varName) {
  let total = 0;
  for (let i = 0; i < P.length; i++) {
    total += P[i][varName];
  }
  return total / P.length;
}

function main() {
  /*
  Input description.
  First line contains an integer n
  the next n lines contains 2 space separated integers
  containing values for arrival time and burst time for
  example:
  2
  0 3
  1 2
  */
  const readline = require("readline");
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });

  rl.question("", (n) => {
    const P = new Array(parseInt(n)).fill(null).map(() => new Process());
    let counter = 0;
    rl.on("line", (line) => {
      const [at, bt] = line.trim().split(" ");
      P[counter]["pid"] = counter++;
      P[counter - 1]["at"] = parseInt(at);
      P[counter - 1]["bt"] = parseInt(bt);

      if (counter == P.length) {
        rl.close();
      }
    });

    rl.on("close", () => {
      P.sort((first, second) => first["at"] - second["at"]);

      console.log("pid\tat\tbt\tct\ttat\twt");
      P[0]["ct"] = P[0]["at"] + P[0]["bt"];
      P[0].update_after_ct();
      P[0].display();

      for (let i = 1; i < P.length; i++) {
        if (P[i]["at"] < P[i - 1]["ct"]) {
          P[i]["ct"] = P[i - 1]["ct"] + P[i]["bt"];
        } else {
          console.log(
            `curr['at'] : ${P[i]["at"]}, prev['ct'] : ${P[i - 1]["ct"]}`
          );
          P[i]["ct"] = P[i]["at"] + P[i]["bt"];
        }
        P[i].update_after_ct();
        P[i].display();
      }

      console.log(`Average waiting time : ${average(P, "wt")}`);
    });
  });
}

main();


 PID     AT      BT      CT      TAT     WT
0       0       10      10      10      0
1       10      5       15      5       0
2       15      8       23      8       0
Avg_turnaround:7.666666666666667
Avg_Waitingtime:0.0

Important Points to remember

  • It is non-preemptive.
  • Average Waiting Time is not optimal
  • Cannot utilize resources in parallel: Results in Convoy effect (Consider a situation when many IO bound processes are there and one CPU bound process. The IO bound processes have to wait for CPU bound process when CPU bound process acquires CPU. The IO bound process could have better taken CPU for some time, then used IO devices).

Characteristics of FCFS

  • Processes are executed according to the order of their arrival.
  • This algorithm has high waiting time.
  • The performance of this algorithm is poor due to high waiting time.
  • Implementing FCFS is much easy.

Advantage of FCFS

  • It is the simplest scheduling algorithm for process execution.
  • The implementation part is very easy.
  • Processes are executed according to the order of arrival.

Disadvantage of FCFS

  • FCFS is a non-preemptive type of algorithm. In simple terms, the CPU executes the complete process in once.
  • Due to the sequential ordering of execution the waiting time is generally high.
  • Easy implementation makes its performance poor.
  • If a big process comes first and then small ones, the small ones have to wait more.

Conclusion

FCFS is the simplest CPU scheduling algorithm. It is non-preemptive in nature. It processes jobs according to their order of arrival. It is poor in performance and easy to implement.

Frequently Asked Questions on FCFS CPU Scheduling – FAQs

What is FCFS algorithm?

FCFS is termed as First come First Serve algorithm. It executes jobs according to their order of arrival sequentially.

How is the nature of FCFS?

Nature of FCFS s Non-preemptive

What is the main Disadvantages of FCFS?

Main disadvantages of FCFS is, CPU can process only one process at a time, poor in performance and waiting time is high.



Similar Reads

Program for FCFS CPU Scheduling | Set 2 (Processes with different arrival times)
We have already discussed FCFS Scheduling of processes with same arrival time. In this post, scenarios, when processes have different arrival times, are discussed. Given n processes with their burst times and arrival times, the task is to find the average waiting time and an average turn around time using FCFS scheduling algorithm. FIFO simply queu
15+ min read
Difference between First Come First Served (FCFS) and Longest Job First (LJF) CPU scheduling algorithms
1.First Come First Served (FCFS) : First Come First Served (FCFS) is the simplest type of algorithm. It is a non-preemptive algorithm i.e. the process cannot be interrupted once it starts executing. The FCFS is implemented with the help of a FIFO queue. The processes are put into the ready queue in the order of their arrival time. The process that
3 min read
Difference between FCFS and Priority CPU scheduling
1. First Come First Served (FCFS) : First Come First Served (FCFS) is the simplest type of algorithm. It is a non-preemptive algorithm i.e. the process cannot be interrupted once it starts executing. The FCFS is implemented with the help of a FIFO queue. The processes are put into the ready queue in the order of their arrival time. The process that
3 min read
Difference Between FCFS and SJF CPU Scheduling Algorithms
CPU scheduling is a key part of how an operating system works. It decides which task (or process) the CPU should work on at any given time. This is important because a CPU can only handle one task at a time, but there are usually many tasks that need to be processed. In this article, we are going to discuss FCFS and SJF CPU scheduling in detail. Fi
5 min read
Difference between Priority Scheduling and Round Robin (RR) CPU scheduling
1. Priority Scheduling Algorithm : Priority scheduling algorithm executes the processes depending upon their priority. Each process is allocated a priority and the process with the highest priority is executed first. Priorities can be defined internally as well as externally. Internal priorities are decided by the system depending upon the number o
3 min read
Difference between Priority scheduling and Shortest Job First (SJF) CPU scheduling
1. Priority Scheduling Algorithm : Priority scheduling algorithm executes the processes depending upon their priority. Each process is allocated a priority and the process with the highest priority is executed first. Priorities can be defined internally as well as externally. Internal priorities are decided by the system depending upon the number o
3 min read
Multilevel Feedback Queue Scheduling (MLFQ) CPU Scheduling
Multilevel Feedback Queue Scheduling (MLFQ) CPU Scheduling is like Multilevel Queue(MLQ) Scheduling but in this process can move between the queues. And thus, much more efficient than multilevel queue scheduling. Characteristics of Multilevel Feedback Queue Scheduling: In a multilevel queue-scheduling algorithm, processes are permanently assigned t
5 min read
FCFS Disk Scheduling Algorithms
Prerequisite: Disk scheduling algorithms.Given an array of disk track numbers and initial head position, our task is to find the total number of seek operations done to access all the requested tracks if First Come First Serve (FCFS) disk scheduling algorithm is used. First Come First Serve (FCFS) FCFS is the simplest disk scheduling algorithm. As
6 min read
Difference between First Come First Served (FCFS) and Round Robin (RR) Scheduling Algorithm
First Come First Served Scheduling Algorithm: First Come First Served (FCFS) is the simplest and non-preemptive scheduling algorithm. In First Come First Served (FCFS), the process is allocated to the CPU in the order of their arrival. A queue data structure is used to implement the FCFS scheduling algorithm. The process which is at the head of the
2 min read
Difference between FCFS and SCAN disk scheduling algorithms
FCFS disk scheduling algorithm: As the name suggests, the FCFS Scheduling Algorithm processes requests in the sequential order in which they arrive in the disk queue. Even if a higher priority request arrives in the schedule later, FCFS will process the request in the order that they have arrived and hence we can say that FCFS has a fair policy. Ex
3 min read
FCFS Scheduling Full Form
FCFS stands for First Come First Serve. In the FCFS scheduling algorithm, the job that arrived first in the ready queue is allocated to the CPU and then the job that came second, and so on. We can say that the ready queue acts as a FIFO (First In First Out) queue thus the arriving jobs/processes are placed at the end of the queue. FCFS is a non-pre
3 min read
Difference between FCFS and SSTF Disk Scheduling Algorithm
Prerequisite - Disk Scheduling Algorithms 1. FCFS Disk Scheduling Algorithm : First come first serve, as name suggest this algorithm entertains the task in the order they arrived in the disk queue. It is the simplest and easy to understand disk scheduling algorithm. In this the head or pointer moves in the direction in which the task arrives and mo
3 min read
Difference between FCFS and C-LOOK disk scheduling algorithm
1. FCFS Disk Scheduling Algorithm FCFS stands for First Come First Serve, this algorithm entertains the task in the order they arrived in the disk queue. It is the simplest and easy to understand disk scheduling algorithm. In this, the head or pointer moves in the direction in which the task arrives and moves till all request is served. However, th
3 min read
Difference between Multi Level Queue Scheduling (MLQ) and First Come First Served (FCFS)
1. Multi Level Queue Scheduling (MLQ) : It is quite difficult to have just one queue and schedule all the processes. This is where multi level queue scheduling is used. In this the processes are divided into various classes depending upon the property of the processes such as system process, I/O process etc. Thus we get 'n' number of queues for n c
3 min read
Relation in FCFS and Round Robin Scheduling Algorithm
In this article, we'll see how FCFS is special kind of Round Robin Algorithm and Round Robin is special kind of FCFS Algorithm. Also, we will cover the relation with each other. Let's discuss one by one. First Come First Serve (FCFS) Scheduling Algorithm : FCFS is simplest of CPU Scheduling Algorithm which executes process that comes first. It is n
3 min read
Difference between FCFS and C-SCAN disk scheduling algorithm
1. FCFS Disk Scheduling Algorithm : FCFS stands for First come first serve, this algorithm entertains the task in the order they arrived in the disk queue. It is the simplest and easy to understand disk scheduling algorithm. In this the head or pointer moves in the direction in which the task arrives and moves till all request is served. However, F
3 min read
Relation in FCFS and Preemptive Priority Scheduling Algorithm
In this article, we will see how FCFS is a special kind of Priority Preemptive Scheduling Algorithm. Also, we will cover the relation with each other. Let us discuss one by one. 1. First Come First Serve (FCFS) Scheduling Algorithm : FCFS is the simplest of CPU Scheduling Algorithm which executes the process that comes first. It is a non-preemptive
4 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 advantage of having a minimum average waiting time
13 min read
Program for Priority CPU Scheduling | Set 1
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
11 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 (LRTF) algorithm LRTF is a preemptive scheduling algo
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 time, priority, arrival time.} void quicksort(proc
15+ 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 compare to priorities (highest process first). Also, if
11 min read
Difference Between User-CPU-Time and System-CPU-Time in UNIX
There are two kinds of CPU time in any UNIX system: User CPU Time and System CPU Time. These metrics help in understanding the way in which the overall execution time is spent by any process using CPU resources. User CPU time is the total amount of time that the CPU spends executing both user processes and those parts of programs that run on behalf
8 min read
Operating Systems | CPU Scheduling | Question 1
Consider three processes (process id 0, 1, 2 respectively) with compute time bursts 2, 4 and 8 time units. All processes arrive at time zero. Consider the longest remaining time first (LRTF) scheduling algorithm. In LRTF ties are broken by giving priority to the process with the lowest process id. The average turn around time is: (A) 13 units (B) 1
1 min read
Operating Systems | CPU Scheduling | Question 2
Consider three processes, all arriving at time zero, with total execution time of 10, 20 and 30 units, respectively. Each process spends the first 20% of execution time doing I/O, the next 70% of time doing computation, and the last 10% of time doing I/O again. The operating system uses a shortest remaining compute time first scheduling algorithm a
2 min read
Operating Systems | CPU Scheduling | Question 3
Consider three CPU-intensive processes, which require 10, 20 and 30 time units and arrive at times 0, 2 and 6, respectively. How many context switches are needed if the operating system implements a shortest remaining time first scheduling algorithm? Do not count the context switches at time zero and at the end. (A) 1 (B) 2 (C) 3 (D) 4 Answer: (B)
1 min read
Operating Systems | CPU Scheduling | Question 4
Which of the following process scheduling algorithm may lead to starvation (A) FIFO (B) Round Robin (C) Shortest Job Next (D) None of the above Answer: (C) Explanation: Shortest job next may lead to process starvation for processes which will require a long time to complete if short processes are continually added.Quiz of this Question
1 min read
Operating Systems | CPU Scheduling | Question 5
If the quantum time of round robin algorithm is very large, then it is equivalent to: (A) First in first out (B) Shortest Job Next (C) Lottery scheduling (D) None of the above Answer: (A) Explanation: If time quantum is very large, then scheduling happens according to FCFS.Quiz of this Question
1 min read
Operating Systems | CPU Scheduling | Question 6
Which of the following is FALSE about SJF (Shortest Job First Scheduling)? S1: It causes minimum average waiting time S2: It can cause starvation (A) Only S1 (B) Only S2 (C) Both S1 and S2 (D) Neither S1 nor S2 Answer: (D) Explanation: Both SJF and Shortest Remaining time first algorithms may cause starvation. Consider a situation when long process
1 min read
Difference between Preemptive Priority based and Non-preemptive Priority based CPU scheduling algorithms
Prerequisite - CPU Scheduling Priority Scheduling : In priority scheduling, each process has a priority which is an integer value assigned to it. The smallest integer is considered as the highest priority and the largest integer is considered as the lowest priority. The process with the highest priority gets the CPU first. In rare systems, the larg
4 min read