Lesson 6 · Processes, threads, and CPU scheduling

FCFS Scheduling

First Come First Serve runs processes in the order they arrive, each to completion. It is the simplest CPU scheduling algorithm, and its one weakness, the convoy effect, explains why the others exist.

FCFS Scheduling concept diagramTop: new processes join the tail of a FIFO ready queue holding P3, P2 and P1, and the head, P1, goes to the CPU, which runs it to completion. Bottom: two Gantt charts for bursts 24, 3 and 3. In arrival order P1, P2, P3 the waits are 0, 24 and 27, average 17. In order P2, P3, P1 the waits are 0, 3 and 6, average 3.one FIFO ready queue, served strictly in arrival ordernew processP3P2P1tailheadCPUruns each to completionconvoy effect: the same three jobs, bursts 24, 3 and 3arrival P1, P2, P3P1P2P30242730avg wait 17waits 0, 24, 27arrival P2, P3, P1P2P3P103630avg wait 3waits 0, 3, 6
1

One Queue, Served in Arrival Order

  1. Sort – order the processes by arrival time; ties keep their original order.
  2. Dispatch – give the CPU to the process at the head of the ready queue.
  3. Run to completion – it keeps the CPU until its whole burst is done.
  4. Repeat – dispatch the next head; if the queue is empty, the CPU idles until the next arrival.

FCFS, or first come first serve scheduling, gives the CPU to processes in the order they arrive in the ready queue. The first process to request the CPU gets it first, like a queue at a ticket counter.

FCFS is non-preemptive: once a process starts running, it keeps the CPU until it finishes its burst or blocks for I/O. The scheduler never interrupts it to run something else, however short or urgent. It is implemented with a single FIFO queue: a new process joins the tail, and the scheduler always dispatches the head.

  • Also written FIFO scheduling or first-in first-out scheduling
  • Selection criterion: arrival time only; burst length and priority are ignored
  • Mode: non-preemptive
  • Data structure: one FIFO queue, O(1) to insert and to dispatch
2

Arrival, Burst, Turnaround and Waiting Time

Every scheduling numerical uses the same quantities. Arrival time (AT) and burst time (BT), the CPU time a process needs, are given; everything else is worked out from the Gantt chart. A process starts at the later of its own arrival and the moment the CPU frees up, so start time = max(AT, completion time of the process before it).

Note the difference between waiting time and response time. Waiting counts all time spent ready but not running. Response time is only the delay until the first run. Here a process runs once, without interruption, so the two are always equal; in Round Robin they are not.

  • Completion time (CT) = start time + BT
  • Turnaround time (TAT) = CT − AT: the whole stay in the system
  • Waiting time (WT) = TAT − BT: the part of that stay spent in the queue
  • Response time = start time − AT, equal to WT under this policy
  • Averages divide the sum by the number of processes; CPU utilization = busy time / total time
3

A Worked Numerical: Four Jobs at Time 0

Take four processes that all arrive at t = 0, in the order P1, P2, P3, P4, with burst times 5, 8, 2 and 4. With equal arrival times, FCFS runs them in the order listed.

The Gantt chart is P1 [0–5], P2 [5–13], P3 [13–15], P4 [15–19]. Because every arrival time is 0, each turnaround time equals the completion time and each waiting time equals the start time.

FCFS with P1 = 5, P2 = 8, P3 = 2, P4 = 4, all arriving at t = 0
ProcessATBTCTTAT = CT − ATWT = TAT − BT
P105550
P20813135
P302151513
P404191915
Average13.008.25
  • Average turnaround = 52 / 4 = 13.00; average waiting = 33 / 4 = 8.25
  • P3, the shortest job, waits 13 units: 6.5 times its own burst
  • Check: the bursts add up to 19, the last completion time, because the CPU never idled
Key reference

Terms, operations, and practical uses

Core vocabulary

  • FCFSFirst Come First Serve: run processes in arrival order, each to completion.
  • Non-preemptiveThe running process cannot be interrupted by the scheduler.
  • Ready queueProcesses waiting for the CPU; a FIFO queue in FCFS.
  • Convoy effectShort jobs delayed behind one long CPU-bound job.

Formulas

  • Completion timeCT = max(AT, previous CT) + BT
  • Turnaround timeTAT = CT − AT
  • Waiting timeWT = TAT − BT, which equals response time in FCFS
  • CPU utilizationbusy time / (busy time + idle time)
Implementation

FCFS with arrival times and an idle gap

def fcfs(processes):
    # processes: (name, arrival, burst) tuples. Ties in arrival keep input order.
    clock, gantt, rows = 0, [], []
    for name, arrival, burst in sorted(processes, key=lambda p: p[1]):
        if clock < arrival:  # nothing is ready: the CPU idles until the next arrival
            gantt.append(("idle", clock, arrival))
            clock = arrival
        start = clock
        clock += burst  # non-preemptive: runs to completion
        gantt.append((name, start, clock))
        turnaround = clock - arrival
        rows.append((name, arrival, burst, start, clock, turnaround, turnaround - burst))
    return gantt, rows


procs = [("P1", 0, 6), ("P2", 2, 3), ("P3", 3, 1), ("P4", 5, 2), ("P5", 14, 2)]
gantt, rows = fcfs(procs)
print("Gantt:", " ".join(f"{n}[{s}-{e}]" for n, s, e in gantt))
print("Process  AT  BT  ST  CT  TAT  WT")
for name, at, bt, st, ct, tat, wt in rows:
    print(f"{name:<7}{at:>4}{bt:>4}{st:>4}{ct:>4}{tat:>5}{wt:>4}")

n = len(rows)
busy = sum(bt for _, _, bt, *_ in rows)
makespan = gantt[-1][2]
print(f"average turnaround {sum(r[5] for r in rows) / n:.2f}")
print(f"average waiting {sum(r[6] for r in rows) / n:.2f}")
print(f"CPU utilization {busy}/{makespan} = {100 * busy / makespan:.1f}%")
#include <algorithm>
#include <cstdio>
#include <string>
#include <vector>
using namespace std;

struct Process {
    string name;
    int arrival, burst;
    int start = 0, completion = 0;
};

int main() {
    vector<Process> procs = {{"P1", 0, 6}, {"P2", 2, 3}, {"P3", 3, 1}, {"P4", 5, 2}, {"P5", 14, 2}};
    // Ties in arrival keep input order.
    stable_sort(procs.begin(), procs.end(),
                [](const Process& a, const Process& b) { return a.arrival < b.arrival; });

    int clock = 0, busy = 0;
    printf("Gantt:");
    for (Process& p : procs) {
        if (clock < p.arrival) {  // nothing is ready: the CPU idles until the next arrival
            printf(" idle[%d-%d]", clock, p.arrival);
            clock = p.arrival;
        }
        p.start = clock;
        clock += p.burst;  // non-preemptive: runs to completion
        p.completion = clock;
        busy += p.burst;
        printf(" %s[%d-%d]", p.name.c_str(), p.start, p.completion);
    }
    printf("\n");

    printf("Process  AT  BT  ST  CT  TAT  WT\n");
    double totalTat = 0, totalWt = 0;
    for (const Process& p : procs) {
        int tat = p.completion - p.arrival;
        int wt = tat - p.burst;
        totalTat += tat;
        totalWt += wt;
        printf("%-7s%4d%4d%4d%4d%5d%4d\n", p.name.c_str(), p.arrival, p.burst, p.start, p.completion, tat, wt);
    }
    int n = procs.size();
    printf("average turnaround %.2f\n", totalTat / n);
    printf("average waiting %.2f\n", totalWt / n);
    printf("CPU utilization %d/%d = %.1f%%\n", busy, clock, 100.0 * busy / clock);
    return 0;
}
import java.util.Arrays;
import java.util.Comparator;

public class Main {
    record Process(String name, int arrival, int burst) {}

    public static void main(String[] args) {
        Process[] procs = {
            new Process("P1", 0, 6), new Process("P2", 2, 3), new Process("P3", 3, 1),
            new Process("P4", 5, 2), new Process("P5", 14, 2)
        };
        // Arrays.sort on objects is stable: ties in arrival keep input order.
        Arrays.sort(procs, Comparator.comparingInt(Process::arrival));

        int n = procs.length;
        int[] start = new int[n], completion = new int[n];
        int clock = 0, busy = 0;
        StringBuilder gantt = new StringBuilder("Gantt:");
        for (int i = 0; i < n; i++) {
            Process p = procs[i];
            if (clock < p.arrival()) { // nothing is ready: the CPU idles until the next arrival
                gantt.append(String.format(" idle[%d-%d]", clock, p.arrival()));
                clock = p.arrival();
            }
            start[i] = clock;
            clock += p.burst(); // non-preemptive: runs to completion
            completion[i] = clock;
            busy += p.burst();
            gantt.append(String.format(" %s[%d-%d]", p.name(), start[i], completion[i]));
        }
        System.out.println(gantt);

        System.out.println("Process  AT  BT  ST  CT  TAT  WT");
        double totalTat = 0, totalWt = 0;
        for (int i = 0; i < n; i++) {
            Process p = procs[i];
            int tat = completion[i] - p.arrival();
            int wt = tat - p.burst();
            totalTat += tat;
            totalWt += wt;
            System.out.printf("%-7s%4d%4d%4d%4d%5d%4d%n",
                    p.name(), p.arrival(), p.burst(), start[i], completion[i], tat, wt);
        }
        System.out.printf("average turnaround %.2f%n", totalTat / n);
        System.out.printf("average waiting %.2f%n", totalWt / n);
        System.out.printf("CPU utilization %d/%d = %.1f%%%n", busy, clock, 100.0 * busy / clock);
    }
}
Watch it run

Step through it

Running on P1 (AT 0, BT 6), P2 (2, 3), P3 (3, 1), P4 (5, 2), P5 (14, 2)

ready queue (FIFO)CPUidleno process is readyGantt chart0ProcessATBTSTCTTATWTP106P223P331P452P5142
Step 1

Five processes, sorted by arrival time

FCFS needs only one rule: the process that arrived first runs first. So the table is ordered by arrival time (AT), and burst time (BT) is how long each needs the CPU. Start time, completion time, turnaround and waiting are what we compute.

Output
1 / 13
4

Scheduling with Arrival Times and Idle Gaps

FCFS scheduling with arrival time adds one rule: a process cannot start before it arrives. Sort by arrival, then walk the list keeping a clock. If the next process has not arrived when the CPU frees up, the clock jumps forward to its arrival and the gap is drawn on the Gantt chart as idle time.

The tracer below works this case with five processes. P5 arrives at 14, two units after the CPU runs out of work at 12, so the CPU idles from 12 to 14. The averages come out at 5.80 for turnaround and 3.00 for waiting, and utilization drops to 14 / 16 = 87.5% because of the gap.

  • Ties – two processes with the same arrival time run in the order listed (lower process ID first)
  • Idle gap – counts in total time and lowers utilization, but adds nothing to anyone's waiting time
  • Arrival at a completion – a process arriving exactly when another finishes can start at once if the queue is empty
  • Check – sum of bursts + idle time = time of the last completion
5

The Convoy Effect

  1. Cause – a long burst at the head of a non-preemptive FIFO queue.
  2. Symptom – high average waiting time, even though the CPU is always busy.
  3. Side effect – I/O devices idle while I/O-bound jobs wait for the CPU.
  4. Cure – run short jobs first (SJF) or preempt long ones (Round Robin).

The convoy effect happens when one long, CPU-bound process holds the CPU and a line of short processes queues up behind it, like cars stuck behind a slow truck on a single-lane road. The short jobs could have finished quickly, but they all wait for the long one.

The diagram at the top of the page shows how large the effect is. Three jobs with bursts 24, 3 and 3 give an average wait of 17 if the long job arrives first, and 3 if it arrives last. The work is identical; only the order changed. FCFS cannot fix this because it never reorders anything.

The effect also wastes devices. While the CPU-bound job runs, I/O-bound processes that need only a moment of CPU sit in the ready queue, so the disks and network sit idle. When the long job finally blocks for I/O, the short ones rush through the CPU and then queue at the device, leaving the CPU idle instead.

  • Worst case: the longest job arrives first; best case: the shortest arrives first
  • The work is the same either way; only the order, and so the average wait, changes
6

Strengths and Limits

This policy trades performance for simplicity. It is the easiest scheduler to build and to predict, and its drawbacks all come from ignoring how long each process needs.

  • Simple – one FIFO queue, O(1) to add and to dispatch
  • No starvation – every process reaches the head eventually, unlike SJF and priority scheduling
  • Low overhead – one context switch per process, the minimum possible
  • High average wait – it depends on arrival order, and one long job delays everyone behind it
  • Poor response time – no preemption, so it suits batch work, not interactive or real-time systems
7

FCFS vs SJF vs Round Robin vs Priority Scheduling

Each major algorithm changes one thing about FCFS. SJF orders by burst length instead of arrival, Round Robin adds a time quantum so nobody holds the CPU for long, and priority scheduling orders by importance. FCFS is also the tie-breaker inside most of them: equal priorities or equal bursts are served in arrival order.

How FCFS compares with the other classic CPU schedulers
AlgorithmPicks next byPreemptive?Starvation?Average waiting time
FCFSearliest arrivalnonooften high (convoy effect)
SJF / SRTFshortest burstSJF no, SRTF yesyes, for long jobsminimum possible
Round Robinarrival, one quantum at a timeyesnomoderate; best response time
Priorityhighest priorityeitheryes, without agingdepends on priorities
  • Round Robin with a quantum at least as long as the longest burst behaves exactly like FCFS
  • When all jobs arrive together, SJF never has a higher average wait than FCFS
  • See CPU Scheduling Algorithms for all of them side by side
8

Where It Is Used

FCFS is rarely the main scheduler of a desktop or phone, but it appears wherever order matters more than speed, or where jobs are similar in length.

Linux's real-time policy SCHED_FIFO is FCFS within one priority level: a SCHED_FIFO task runs until it blocks, yields, or a higher-priority task arrives. The same rule governs FCFS disk scheduling, where requests are served in arrival order, and the print spooler, where documents print in the order they were sent.

  • Batch systems – no interactive users, so throughput matters more than response time
  • SCHED_FIFO – real-time tasks of equal priority run first come first served
  • Queues everywhere – print spoolers, message queues, network packet buffers
  • Tie-breaking – SJF, priority and multilevel queues fall back to arrival order