CPU Scheduling

CPU Scheduling is the process of determining which process will own the CPU for execution while another process is on hold. It is a fundamental function of the operating system.

Why CPU Scheduling?

  • Processes alternate between CPU bursts and I/O bursts
  • While one process waits for I/O, CPU can execute another process
  • Maximizes CPU utilization and system throughput
  • Ensures fair resource allocation among processes

Important Terminology

Term Definition
Arrival Time (AT) Time when process enters the ready queue
Burst Time (BT) Total CPU time required by the process
Completion Time (CT) Time when process finishes execution
Turnaround Time (TAT) CT - AT (Total time from arrival to completion)
Waiting Time (WT) TAT - BT (Time spent waiting in ready queue)
Response Time (RT) Time from arrival to first CPU allocation
Throughput Number of processes completed per unit time

Scheduling Objectives

  1. Maximize CPU Utilization – Keep CPU as busy as possible
  2. Maximize Throughput – Complete more processes per time unit
  3. Minimize Turnaround Time – Reduce total time for process execution
  4. Minimize Waiting Time – Reduce time spent in ready queue
  5. Minimize Response Time – Quick response for interactive systems
  6. Fairness – Each process gets fair share of CPU

Types of Process Schedulers

Operating systems use three distinct types of schedulers to manage process lifecycle and resource utilization across storage, memory, and CPU:

flowchart TD subgraph Disk["💾 Secondary Storage / Disk"] JP["📦 Job Pool / New Tasks"] Swap["🔄 Swap Area / Suspended Tasks"] end subgraph Memory["🧠 Main Memory (RAM)"] Ready["📋 Ready Queue"] Wait["⏳ Waiting / Blocked Queue"] end CPU["⚙️ CPU (Execution)"] Term(["🛑 Terminated"]) JP -->|"Long-Term Scheduler
(Admit / Job Scheduling)"| Ready Ready -->|"Short-Term Scheduler
(Dispatch / CPU Scheduling)"| CPU CPU -->|"Exit"| Term CPU -->|"I/O or Event Wait"| Wait Wait -->|"I/O Completion"| Ready CPU -->|"Time Slice Expired / Interrupt"| Ready Ready -.->|"Medium-Term Scheduler
(Swap Out)"| Swap Wait -.->|"Medium-Term Scheduler
(Swap Out)"| Swap Swap -.->|"Medium-Term Scheduler
(Swap In)"| Ready

1. Long-Term Scheduler (Job Scheduler)

  • Primary Role: Selects processes from the Job Pool on secondary storage (disk) and loads them into Main Memory (Ready Queue).
  • Execution Frequency: Executes relatively infrequently (seconds or minutes).
  • Controls Degree of Multiprogramming: Directly sets the total number of active processes residing in main memory at any given time.
  • Mix Balancing: Ensures a stable balance between:
    • I/O-Bound Processes: Spend more time doing I/O than computations (e.g., file transfer, interactive UI).
    • CPU-Bound Processes: Spend more time performing heavy caculations (e.g., matrix multiplication, video encoding).
    • If all jobs are CPU-bound: I/O queue sits idle, device utilization drops.
    • If all jobs are I/O-bound: Ready queue is empty, CPU sits idle.
  • Modern OS Status: Minimal or absent in modern time-sharing OS (like Linux or Windows), where new processes are immediately placed into memory upon creation.

2. Short-Term Scheduler (CPU Scheduler)

  • Primary Role: Selects a process from the Ready Queue in main memory and allocates the CPU for execution.
  • Execution Frequency: Executes extremely frequently (every 10–100 milliseconds).
  • Speed Requirement: Must be blazing fast (≈\approx microseconds) to minimize CPU scheduling overhead and prevent CPU starvation.
  • Working with the Dispatcher:
    • While the scheduler selects which process runs next, the Dispatcher gives actual control of the CPU to that selected process.
    • Dispatcher responsibilities:
      1. Saving old process context and restoring new process context (Context Switch).
      2. Switching mode from kernel mode to user mode.
      3. Jumping to the appropriate location in the user program to restart it.
    • Dispatch Latency: The time taken by the dispatcher to stop one process and start another.

3. Medium-Term Scheduler (Swapper)

  • Primary Role: Removes processes temporarily from main memory to secondary storage (Swap Out) and brings them back (Swap In).
  • Execution Frequency: Executes at intermediate frequency (when memory pressure or thrashing occurs).
  • Reduces Degree of Multiprogramming: Temporarily lowers memory contention when physical RAM is overloaded.
  • Handles Suspended States:
    • Suspend Ready: Process was ready to run but swapped out to disk due to memory pressure.
    • Suspend Blocked: Process was waiting for an event/I/O and swapped out to disk.
  • Benefit: Frees up contiguous RAM pages for active processes, dramatically reducing page faults and preventing system thrashing.

Comparison of Schedulers

Feature Long-Term Scheduler Medium-Term Scheduler Short-Term Scheduler
Alternate Name Job Scheduler Swapper CPU Scheduler
Execution Speed Slowest Medium Fastest (microseconds)
Frequency Infrequent (seconds/minutes) Intermediate Very Frequent (milliseconds)
Location Disk →\to Main Memory Main Memory ↔\leftrightarrow Disk Main Memory →\to CPU
Degree of Multiprogramming Controls / Regulates Reduces / Balances No effect
Selection Goal Maintain I/O vs CPU balance Alleviate RAM pressure & thrashing Maximize CPU utilization & throughput
State Transitions New →\to Ready Ready/Wait ↔\leftrightarrow Suspended Ready →\to Running
Presence in Modern OS Rare / Minimal (Batch systems) Common (Virtual memory paging/swapping) Universal (All operating systems)

Types of Scheduling

Preemptive Scheduling

  • Running process can be interrupted and moved to ready queue
  • CPU can be taken away from a process
  • Examples: Round Robin, SRTF, Priority (Preemptive)
  • Better for time-sharing systems

Non-Preemptive Scheduling

  • Once CPU is allocated, process runs until completion or I/O wait
  • CPU cannot be taken away from running process
  • Examples: FCFS, SJF, Priority (Non-Preemptive)
  • Simpler to implement

CPU Scheduling Algorithms

1. First Come First Serve (FCFS)

Concept: Processes are executed in the order they arrive.
Characteristics:

  • Non-preemptive
  • Simple to implement using FIFO queue
  • Poor average waiting time (especially if long process arrives first)
  • Convoy Effect: Short processes wait behind long ones
    Example:
    Process AT BT
    P1 0 24
    P2 1 3
    P3 2 3
    Gantt Chart: ` P1 (0-24) P2 (24-27)
    Calculations:
  • P1: TAT = 24-0 = 24, WT = 24-24 = 0
  • P2: TAT = 27-1 = 26, WT = 26-3 = 23
  • P3: TAT = 30-2 = 28, WT = 28-3 = 25
  • Average WT = (0+23+25)/3 = 16

2. Shortest Job First (SJF)

Concept: Process with smallest burst time executes first.
Characteristics:

  • Non-preemptive
  • Optimal average waiting time for non-preemptive algorithms
  • Difficult to know burst time in advance
  • May cause starvation for longer processes
    Example:
    Process AT BT
    P1 0 7
    P2 2 4
    P3 4 1
    P4 5 4
    Execution Order (after P1): P3 → P2 → P4

3. Shortest Remaining Time First (SRTF)

Concept: Preemptive version of SJF. Process with shortest remaining time executes.
Characteristics:

  • Preemptive
  • Most optimal algorithm (minimum average WT)
  • High context switching overhead
  • Starvation possible for long processes
    Example:
    Process AT BT
    P1 0 8
    P2 1 4
    P3 2 2
    P4 3 1
    Gantt Chart: ` P1(0-1) P2(1-2)

4. Round Robin (RR)

Concept: Each process gets a fixed time quantum. After quantum expires, process moves to end of ready queue.
Characteristics:

  • Preemptive
  • Fair allocation of CPU
  • Performance depends on time quantum size
  • No starvation
  • Higher context switching overhead
    Time Quantum Selection:
  • Too small → High context switching overhead
  • Too large → Becomes FCFS
  • Ideal: 80% of CPU bursts should be shorter than quantum
    Example (Time Quantum = 4):
    Process AT BT
    P1 0 5
    P2 1 4
    P3 2 2
    P4 3 1
    Gantt Chart: ` P1(0-4) P2(4-8)

5. Priority Scheduling

Concept: Each process has a priority. Higher priority processes execute first.
Types:

  • Preemptive: Running process can be preempted if higher priority arrives
  • Non-Preemptive: Running process completes before higher priority gets CPU
    Priority Assignment:
  • Lower number = Higher priority (common convention)
  • Can be static or dynamic
    Problem: Starvation
  • Low priority processes may never execute
    Solution: Aging
  • Gradually increase priority of waiting processes
    Example:
    Process AT BT Priority
    P1 0 10 3
    P2 0 1 1
    P3 0 2 4
    P4 0 1 5
    P5 0 5 2
    Execution Order: P2 → P5 → P1 → P3 → P4

6. Highest Response Ratio Next (HRRN)

Concept: Non-preemptive algorithm that considers both waiting time and burst time.
Response Ratio Formula:

Response Ratio = (Waiting Time + Burst Time) / Burst Time

Characteristics:

  • Non-preemptive
  • Balances between SJF and FCFS
  • Prevents starvation (long waiting increases ratio)
  • Fair to both short and long processes

7. Multilevel Queue Scheduling

Concept: Ready queue is divided into multiple separate queues based on process properties (e.g., priority, memory size, process type).

flowchart TD subgraph Queues["Priority Hierarchical Queues"] Q1["👑 System Processes (Highest Priority) → FCFS / RR"] Q2["💬 Interactive Processes → Round Robin (q=4)"] Q3["🎮 Interactive Editing Processes → Round Robin (q=8)"] Q4["📦 Batch Processes (Lowest Priority) → FCFS"] end Q1 --> CPU["⚙️ CPU Execution"] Q2 --> CPU Q3 --> CPU Q4 --> CPU

Characteristics:

  • Each queue has its own scheduling algorithm.
  • Processes stay in their assigned queue permanently (no movement between queues).
  • Scheduling between queues is fixed-priority preemptive scheduling (e.g., serve Queue 1 entirely before Queue 2) or time-sliced across queues.

8. Multilevel Feedback Queue Scheduling (MLFQ)

Concept: Processes can dynamically move between queues based on their CPU-burst behavior and aging.

flowchart TD New["🆕 New Process"] --> Q0["Queue 0: Round Robin (Quantum = 8ms)"] Q0 -->|"If CPU burst > 8ms"| Q1["Queue 1: Round Robin (Quantum = 16ms)"] Q1 -->|"If CPU burst > 16ms"| Q2["Queue 2: FCFS (Long batch tasks)"] Q2 -.->|"Aging: Waiting too long (Prevent Starvation)"| Q1 Q1 -.->|"Aging: Waiting too long"| Q0 Q0 --> CPU["⚙️ CPU"] Q1 --> CPU Q2 --> CPU

Characteristics:

  • Most flexible and general-purpose CPU scheduling algorithm.
  • I/O-bound processes stay in high-priority short-quantum queues.
  • CPU-intensive processes automatically sink to lower-priority long-quantum/FCFS queues.
  • Prevents starvation by upgrading aging processes that wait too long in lower queues.

Key Parameters:

  • Number of queues
  • Scheduling algorithm for each queue
  • Criteria to upgrade a process to a higher queue (Aging)
  • Criteria to demote a process to a lower queue
  • Method to select entry queue for incoming processes

Algorithm Comparison

Algorithm Preemptive Starvation Convoy Effect Overhead
FCFS No No Yes Low
SJF No Yes No Low
SRTF Yes Yes No High
Round Robin Yes No No High
Priority Both Yes No Medium
HRRN No No No Medium

Special Scheduling Scenarios

Real-Time Scheduling

Hard Real-Time:

  • Deadlines MUST be met
  • Used in critical systems (medical, aviation)
    Soft Real-Time:
  • Deadlines are preferred but not mandatory
  • Used in multimedia, gaming
    Algorithms:
  • Rate Monotonic (RM): Static priority based on period
  • Earliest Deadline First (EDF): Dynamic priority based on deadline

Thread Scheduling

User-Level Threads:

  • Thread library manages scheduling
  • OS schedules processes, not threads
    Kernel-Level Threads:
  • OS directly schedules threads
  • More efficient for multi-core systems

Placement Interview Questions

Q1: Which scheduling algorithm is optimal?

SRTF is optimal for minimizing average waiting time.
Q2: What is convoy effect?
When short processes wait behind a long process in FCFS, leading to poor CPU utilization.
Q3: How to prevent starvation in Priority Scheduling?
Use aging technique - gradually increase priority of waiting processes.
Q4: What is the ideal time quantum for Round Robin?
Should be such that 80% of CPU bursts complete within one quantum.
Q5: Difference between preemptive and non-preemptive scheduling?
Preemptive allows CPU to be taken from running process; non-preemptive doesn't.
Q6: What is turnaround time?
Total time from process arrival to completion (TAT = CT - AT).


Practice Problem

Given:

| Process | AT | BT |
| :--- | :--- | :--- | :--- | :--- |
| P1 | 0 | 5 |
| P2 | 1 | 3 |
| P3 | 2 | 8 |
| P4 | 3 | 6 |

Calculate completion time (CT), turnaround time (TAT), waiting time (WT), and average waiting time for FCFS, SJF (Non-preemptive), and Round Robin (q=2q=2).

🔍 View Step-by-Step Solution & Gantt Charts

1. First Come First Serve (FCFS)

Gantt Chart:
| P1 (0–5) | P2 (5–8) | P3 (8–16) | P4 (16–22) |

Process AT BT CT TAT (CT - AT) WT (TAT - BT)
P1 0 5 5 5−0=55 - 0 = 5 5−5=05 - 5 = 0
P2 1 3 8 8−1=78 - 1 = 7 7−3=47 - 3 = 4
P3 2 8 16 16−2=1416 - 2 = 14 14−8=614 - 8 = 6
P4 3 6 22 22−3=1922 - 3 = 19 19−6=1319 - 6 = 13
  • Average Turnaround Time: 5+7+14+194=454=11.25 ms\frac{5 + 7 + 14 + 19}{4} = \frac{45}{4} = \mathbf{11.25\text{ ms}}
  • Average Waiting Time: 0+4+6+134=234=5.75 ms\frac{0 + 4 + 6 + 13}{4} = \frac{23}{4} = \mathbf{5.75\text{ ms}}

2. Shortest Job First (SJF - Non-Preemptive)

  • At t=0t=0: Only P1 is in the ready queue →\to executes until t=5t=5.
  • At t=5t=5: P2 (BT=3), P3 (BT=8), P4 (BT=6) are ready →\to shortest is P2 (runs 5→85 \to 8).
  • At t=8t=8: P4 (BT=6) and P3 (BT=8) are ready →\to shortest is P4 (runs 8→148 \to 14).
  • At t=14t=14: P3 (BT=8) executes (14→2214 \to 22).

Gantt Chart:
| P1 (0–5) | P2 (5–8) | P4 (8–14) | P3 (14–22) |

Process AT BT CT TAT (CT - AT) WT (TAT - BT)
P1 0 5 5 5−0=55 - 0 = 5 5−5=05 - 5 = 0
P2 1 3 8 8−1=78 - 1 = 7 7−3=47 - 3 = 4
P3 2 8 22 22−2=2022 - 2 = 20 20−8=1220 - 8 = 12
P4 3 6 14 14−3=1114 - 3 = 11 11−6=511 - 6 = 5
  • Average Turnaround Time: 5+7+20+114=434=10.75 ms\frac{5 + 7 + 20 + 11}{4} = \frac{43}{4} = \mathbf{10.75\text{ ms}}
  • Average Waiting Time: 0+4+12+54=214=5.25 ms\frac{0 + 4 + 12 + 5}{4} = \frac{21}{4} = \mathbf{5.25\text{ ms}}

3. Round Robin (RR, Time Quantum q=2q = 2)

Execution Flow & Ready Queue:

  • t=0→2t=0 \to 2: P1 runs (2ms2\text{ms}), rem=3. Ready queue: [P2, P3, P1]
  • t=2→4t=2 \to 4: P2 runs (2ms2\text{ms}), rem=1. Ready queue: [P3, P1, P4, P2]
  • t=4→6t=4 \to 6: P3 runs (2ms2\text{ms}), rem=6. Ready queue: [P1, P4, P2, P3]
  • t=6→8t=6 \to 8: P1 runs (2ms2\text{ms}), rem=1. Ready queue: [P4, P2, P3, P1]
  • t=8→10t=8 \to 10: P4 runs (2ms2\text{ms}), rem=4. Ready queue: [P2, P3, P1, P4]
  • t=10→11t=10 \to 11: P2 runs (1ms1\text{ms}), P2 completes at t=11t=11. Ready queue: [P3, P1, P4]
  • t=11→13t=11 \to 13: P3 runs (2ms2\text{ms}), rem=4. Ready queue: [P1, P4, P3]
  • t=13→14t=13 \to 14: P1 runs (1ms1\text{ms}), P1 completes at t=14t=14. Ready queue: [P4, P3]
  • t=14→16t=14 \to 16: P4 runs (2ms2\text{ms}), rem=2. Ready queue: [P3, P4]
  • t=16→18t=16 \to 18: P3 runs (2ms2\text{ms}), rem=2. Ready queue: [P4, P3]
  • t=18→20t=18 \to 20: P4 runs (2ms2\text{ms}), P4 completes at t=20t=20. Ready queue: [P3]
  • t=20→22t=20 \to 22: P3 runs (2ms2\text{ms}), P3 completes at t=22t=22.

Gantt Chart:
| P1(0-2) | P2(2-4) | P3(4-6) | P1(6-8) | P4(8-10) | P2(10-11) | P3(11-13) | P1(13-14) | P4(14-16) | P3(16-18) | P4(18-20) | P3(20-22) |

Process AT BT CT TAT (CT - AT) WT (TAT - BT)
P1 0 5 14 14−0=1414 - 0 = 14 14−5=914 - 5 = 9
P2 1 3 11 11−1=1011 - 1 = 10 10−3=710 - 3 = 7
P3 2 8 22 22−2=2022 - 2 = 20 20−8=1220 - 8 = 12
P4 3 6 20 $2