Top Banner Ad

BCS401 — Unit 3: CPU Scheduling

Table of Contents (23 sections)

BCS401 · Operating system · Unit 3

CPU Scheduling

Unit Scope & Exam Weightage: This unit covers scheduling concepts and performance criteria, process states and transition diagram, schedulers, PCB and process identification, process address space, threads, FCFS/SJF/RR/priority scheduling with Gantt charts, multiprocessor scheduling, and deadlock — system model, characterization, prevention, avoidance (Banker's algorithm), detection and recovery. It is the heaviest unit of BCS401: expect 2-mark definitions plus 7-mark numericals and deadlock theory.


Importance-Wise Roadmap (BCS401 Unit 3)

Priority Exact Syllabus Topic PYQ Evidence Marks Pattern Tag
1 Scheduling algorithms + Gantt charts (SJF, priority, FCFS, RR) 2024-25, 2025-26 7m × 3 + 2m Must solve
2 Deadlock: system model, prevention, avoidance, detection, recovery 2023-24, 2025-26 7m × 4 Banker's algorithm
3 Process states & transition diagram 2023-24, 2024-25 7m + 2m Diagram
4 PCB / process identification information 2023-24, 2024-25, 2025-26 7m + 2m × 2 Repeat cluster
5 Schedulers, performance criteria, convoy effect 2025-26 (predicted cluster) 2–7m Theory
6 Threads and multiprocessor scheduling Not directly asked Predicted Backup
7 Process address space Not directly asked Predicted Backup

Scheduling-specific examiner guidance: Always label the Gantt chart time axis, write waiting time as completion − arrival − burst, and give the sum divided by n explicitly. For Banker's algorithm, show Need = Max − Allocation as a matrix before attempting the safety test; evaluators award step marks for that table.


1. Process States, PCB and Schedulers

1.1 Process States and Transition Diagram

Process state (PYQ 2023-24, 2 marks): the current activity of a process, recorded in its PCB. The five basic states are new, ready, running, waiting (blocked), terminated; suspended variants (ready-suspended, blocked-suspended) appear when swapping is used.

              admit            dispatch
   NEW ---------------> READY -------------> RUNNING
                         ^                    |  |  |
                         |   time-out         |  |  | I/O wait
                         +--------------------+  |  v
                         |                       WAITING
                         |                          |
                         +--- I/O completion -------+
                                      |
                              exit <--+   (RUNNING -> TERMINATED)
Transition Cause
New → Ready Admitted by the job scheduler; PCB created
Ready → Running Dispatcher allocates CPU
Running → Ready Timer interrupt (quantum expires) or higher-priority process arrives
Running → Waiting Process requests I/O, waits for event/semaphore
Waiting → Ready I/O completion or event occurs
Running → Terminated exit() or abnormal abort

PYQ (2024-25, 7 marks): "Explain the process concept in detail with its states and state transition diagram." Define process (program in execution with PCB), draw the diagram, describe all six transitions in the table, and add that only one process runs per CPU core while many wait in the ready queue.

1.2 Process Control Block (PCB)

The PCB is the kernel data structure holding everything needed to suspend and resume a process.

Field group Contents
Process identification PID (PYQ 2023-24: name one piece → "Process ID"), parent PID, user ID, group ID
Process state new/ready/running/waiting/terminated
Program counter Address of next instruction
CPU registers General registers, stack pointer, status word, floating-point state
Scheduling info Priority, queue pointers, remaining quantum
Memory info Base/limit registers, page table pointer, address-space limits
Accounting CPU time used, time limits, job/process number
I/O info Open file descriptors, pending I/O, device list

PYQ (2025-26, 7 marks): "What is a Process Control Block? Explain its role in process management." PCB = kernel's representation of a process; role: context saving/restoring during context switch, scheduler input (state/priority), resource tracking, accounting and protection.

PYQ (2023-24, 7 marks): "Explain the structure and contents of a Process Control Block (PCB)?" Reproduce the table; stress that the PCB is created at process creation and deleted at termination and lives in kernel memory.

Predicted (bank marks PRED, 7 marks): "Describe the actions taken by a kernel to context-switch between processes." Steps: (1) timer/event traps to kernel; (2) save PC, registers, status word and stack pointer of old process into its PCB; (3) change its state to ready/waiting and enqueue it; (4) dispatch scheduler selects next ready process; (5) load its PCB's memory map/address-space pointer; (6) restore registers and PC; (7) resume user mode. Overhead is pure bookkeeping — no useful work during the switch.

PYQ (2024-25, 2 marks): "List three components stored in a PCB." PID, program counter, CPU registers (also valid: process state, priority, memory limits, open files).

1.3 Schedulers and Performance Criteria

Scheduler Selects Frequency
Long-term (job) scheduler Which jobs enter the system/ready queue Low (minutes)
Short-term (CPU) scheduler Which ready process gets the CPU High (milliseconds)
Medium-term scheduler Which processes are swapped in/out Moderate

Criteria: CPU utilization, throughput (processes completed per unit time), turnaround time = completion − arrival, waiting time = turnaround − burst, response time = first run − arrival, fairness and predictability. Preemptive algorithms need a timer interrupt; non-preemptive ones run until the process blocks or terminates.


2. CPU Scheduling Algorithms with Gantt Charts

2.1 FCFS, SJF, Round Robin — Comparison

Algorithm Decision rule Preemptive? Strength Weakness
FCFS First arrival gets CPU No Simple, fair in arrival order Convoy effect: a long job makes short jobs wait
SJF (non-preemptive) Shortest burst among arrived No Minimum average waiting time (provably optimal) Starvation of long jobs; needs burst estimate
SRTF (preemptive SJF) Shortest remaining time Yes Best average waiting with arrivals Long jobs may starve; overhead of switches
Priority Highest priority (smallest number here) Either Important jobs first Starvation; aging fixes it
Round Robin (RR) FIFO queue with quantum qq Yes (time slice) Good response time, fair Too small qq → context-switch overhead; too large → degrades to FCFS

Predicted (bank PRED, 7 marks): "Compare and contrast FCFS, SJF, and Round Robin scheduling algorithms." Use the table and add: FCFS and SJF are non-preemptive by default; RR is preemptive at quantum expiry. SJF minimises average waiting time but needs future knowledge; RR optimises response time for interactive systems.

Predicted (bank PRED, 2 marks): "Illustrate the reason for the convoy effect in process scheduling." With FCFS, one CPU-bound process with burst 100 arrives first; ten I/O-bound processes with burst 1 queue behind it. Each short process waits ~100 ms while the CPU executes one long job, and the I/O devices become idle — a "convoy" of short jobs waits for one slow leader. RR or SJF avoids it.

2.2 Solved: Preemptive SJF (SRTF) Numerical

Predicted (bank PRED, 2025-26, 7 marks): "Consider P1(AT=0,BT=8), P2(1,6), P3(2,9), P4(3,3), P5(4,4). Draw the Gantt chart and calculate Average Waiting Time and Average Turnaround Time using preemptive SJF."

Step-by-step decisions (remaining time in parentheses):

Time Event Decision
0 P1 arrives (8) P1 starts
1 P2 arrives (6) < P1 rem 7 Preempt P1; P2 runs
2 P3 arrives (9) P2 continues (rem 5→4)
3 P4 arrives (3) < P2 rem 4 Preempt P2; P4 runs
4 P5 arrives (4) P4 continues
6 P4 finishes Ready: P5(4), P2(4), P1(7), P3(9); pick P5 (tie broken by arrival order alternative gives same averages)
10 P5 finishes P2 rem 4 runs
14 P2 finishes P1 rem 7 runs
21 P1 finishes P3 rem 9 runs
30 P3 finishes —
Gantt chart (preemptive SJF)
P1   P2    P4    P5     P2     P1      P3
| 0 | 1  | 3  | 6   | 10  | 14   | 21   | 30 ms
Process Arrival Burst Completion Turnaround (C−A) Waiting (TAT−BT)
P1 0 8 21 21 13
P2 1 6 14 13 7
P3 2 9 30 28 19
P4 3 3 6 3 0
P5 4 4 10 6 2

Average waiting time = (13+7+19+0+2)/5 = 41/5 = 8.2 ms. Average turnaround time = (21+13+28+3+6)/5 = 71/5 = 14.2 ms.

(If P2 is chosen before P5 at time 6, their individual waiting times swap — 3 and 6 — but both averages remain 8.2 and 14.2.)

2.3 Solved: Preemptive Priority Numerical

Predicted (bank PRED, 2024-25, 7 marks): "P1(0,11,pri2), P2(5,28,pri0), P3(12,2,pri3), P4(2,10,pri1), P5(9,16,pri4); 0 = highest priority. Draw Gantt chart and find average waiting time (preemptive priority)."

Time Event Decision
0 P1 (pri2) only P1 runs
2 P4 (pri1) arrives Preempt P1 (rem 9); P4 runs
5 P2 (pri0) arrives Preempt P4 (rem 7); P2 runs
9 P5 (pri4) arrives P2 continues
12 P3 (pri3) arrives P2 continues (pri0 highest)
33 P2 completes (28 ms) P4 (pri1) resumes
40 P4 completes P1 (pri2) resumes
49 P1 completes P3 runs 2 ms
51 P3 completes P5 runs 16 ms
67 P5 completes —
Gantt chart (preemptive priority)
P1  P4    P2          P4    P1      P3   P5
|0 |2 |5 |         33|40 |49 |51 |67  ms
Process Arrival Burst Completion TAT Waiting
P1 0 11 49 49 38
P2 5 28 33 28 0
P3 12 2 51 39 37
P4 2 10 40 38 28
P5 9 16 67 58 42

Average waiting time = (38+0+37+28+42)/5 = 145/5 = 29.0 ms. Note: priority 0 must be treated as highest; reversing that convention is the most common error in this numerical. Starvation of low-priority P5 is visible — aging (raising priority with waiting time) is the remedy.

2.4 Round Robin Worked Mini-Example

Quantum q=2q=2, P1(AT0,BT5), P2(AT0,BT2), P3(AT0,BT4):

P1 P2 P3 P1 P3 P1 P3
0  2  4  6  8  9 11

P1 wait = (6−0)+(8−2)+(9−? actually completion 11, TAT11, BT5 → WT6), P2 WT=2, P3 WT=(2+8−0? TAT=11, BT4 → WT7). Always draw the queue after each quantum rather than guessing.

2.5 Multiprocessor Scheduling (syllabus topic)

Approach Description Merit / demerit
Asymmetric multiprocessing One CPU runs all scheduling/kernel code Simple, but master CPU is a bottleneck
Symmetric multiprocessing (SMP) Each CPU schedules itself from a common ready queue Balanced; needs spinlocks on the queue
Processor affinity Keep a process on the same CPU to exploit warm cache Less migration overhead; may unbalance load
Load balancing Push/pull tasks between queues Better utilization; extra migration cost
Gang scheduling Related threads run simultaneously on different CPUs Good for tightly coupled parallel jobs

3. Deadlock — Model, Characterization and Handling

Deadlock (PYQ 2023-24): a state in which a set of processes is blocked permanently because each holds a resource that another process in the set needs.

3.1 Four Necessary Conditions (Coffman conditions)

Condition Meaning Prevention attack
Mutual exclusion At least one resource is non-sharable Use spooling to make resources sharable where possible
Hold and wait A process holds resources while requesting more Request all resources at once; or release before requesting
No preemption Resources cannot be forcibly taken Preempt resources from waiting processes (works for CPU/memory)
Circular wait Chain P1→P2→…→Pn→P1 each waiting for the next Impose a global ordering of resource types

All four must hold simultaneously; breaking any one prevents deadlock.

PYQ (2023-24, 7 marks): "Explore the concept of deadlock and how it can occur in concurrent systems, discussing prevention and avoidance techniques?" Define deadlock, list the four conditions with the prevention attack table, then contrast: prevention breaks a condition statically (low resource use, may cause starvation); avoidance dynamically examines each request (Banker's algorithm) and grants only safe requests.

3.2 Resource-Allocation Graph

Directed graph: Pi→RjP_i \rightarrow R_j = request edge; Rj→PiR_j \rightarrow P_i = assignment edge. A cycle means deadlock only if each resource type has a single instance; with multiple instances a cycle is a necessary but not sufficient condition, and Banker's algorithm is needed.

PYQ (2023-24, 7 marks): "Evaluate strategies for deadlock prevention, avoidance, detection, and recovery in concurrent systems, highlighting their effectiveness and trade-offs?"

Strategy When applied Technique Effectiveness / trade-off
Prevention Before execution Break one Coffman condition Guaranteed no deadlock but conservative; low utilization
Avoidance At each request Banker's algorithm / safe-state test Better utilization; needs maximum claims in advance and O(mn2)O(mn^2) work
Detection Periodically Wait-for graph or matrix algorithm, reduce graph Finds existing deadlock; overhead of running detector
Recovery After detection Kill one/all deadlocked processes; resource preemption with rollback Simple but loses work; rollback needs checkpoints; repeated abort may starve a process

3.3 Solved: Tape-Drive Safety (Banker's reasoning)

Predicted (bank PRED, 2024-25, 7 marks): "9 tape drives; P1 allocation 3 max 7, P2 allocation 1 max 6, P3 allocation 3 max 5. Which describes the state?"

Process Allocated Max Need = Max − Alloc
P1 3 7 4
P2 1 6 5
P3 3 5 2

Available = 9−(3+1+3)=29 - (3+1+3) = 2. Work = 2. P3's need 2 ≤ 2 → P3 finishes, releases 3 → Work = 5. P1's need 4 ≤ 5 → finishes, releases 3 → Work = 8. P2's need 5 ≤ 8 → finishes. Safe sequence ⟨P3, P1, P2⟩.

Answer: option 2 — Safe, Not Deadlocked. (It is not deadlocked because some process can finish; it is safe because all can finish in some order.)

3.4 Solved: Banker's Algorithm Full Snapshot

Predicted (bank PRED, 2025-26, 7 marks): "Allocation T0(0 0 1 2), T1(1 0 0 0), T2(1 3 5 4), T3(0 6 3 2), T4(0 0 1 4); Max T0(0 0 1 2), T1(1 7 5 0), T2(2 3 5 6), T3(0 6 5 2), T4(0 6 5 6); Available (1 5 2 0). Find Need, check safety, and decide request T1(0 4 2 0)."

i. Need = Max − Allocation

Thread Need (A B C D)
T0 (0 0 0 0)
T1 (0 7 5 0)
T2 (1 0 0 2)
T3 (0 0 2 0)
T4 (0 6 4 2)

ii. Safety check with Work = (1 5 2 0):

Step Need ≤ Work? Finish New Work after release
1 T0 (0 0 0 0) yes T0 (1 5 3 2)
2 T2 (1 0 0 2) yes T2 (2 8 8 6)
3 T3 (0 0 2 0) yes T3 (2 14 11 8)
4 T1 (0 7 5 0) yes T1 (3 14 11 8)
5 T4 (0 6 4 2) yes T4 (3 14 12 12)

Safe sequence ⟨T0, T2, T3, T1, T4⟩ → the system is in a safe state.

iii. Request T1 = (0 4 2 0):

  1. Request ≤ Need₁ (0 4 2 0) ≤ (0 7 5 0) ✔
  2. Request ≤ Available (0 4 2 0) ≤ (1 5 2 0) ✔
  3. Tentative state: Available' = (1 1 0 0), Allocation₁' = (1 4 2 0), Need₁' = (0 3 3 0).
  4. Safety: Work=(1 1 0 0) → T0 finishes → (1 1 1 2) → T2 finishes → (2 4 6 6) → T3 finishes → (2 10 9 8) → T1 finishes → (3 14 11 8) → T4 finishes.

Request can be granted immediately; safe sequence ⟨T0,T2,T3,T1,T4⟩ remains valid.

3.5 Solved: Deadlock-Free Condition Proof

Predicted (bank PRED, 2025-26, 7 marks): "m identical resources, n processes, each requests/releases one at a time. Show deadlock-free if 1 ≤ max needᵢ ≤ m and Σ max needᵢ < m + n."

Proof by contradiction: Assume a deadlock. Then every one of the nn processes is holding some resources and waiting for more, so process ii holds at most maxi−1\text{max}_i - 1 resources (it cannot already hold its maximum, otherwise it would not wait). Therefore

∑i=1nheldi≤∑i=1n(maxi−1)=∑maxi−n<(m+n)−n=m.\sum_{i=1}^{n} \text{held}_i \le \sum_{i=1}^{n}(\text{max}_i - 1) = \sum \text{max}_i - n < (m+n) - n = m.

But under deadlock no process can release a resource and each blocked request is for one resource; if any resource were free the requester would take it and progress. Hence all mm resources must be allocated: ∑heldi=m\sum \text{held}_i = m. This contradicts ∑heldi<m\sum \text{held}_i < m. Therefore a deadlock cannot occur. ∎

3.6 Thread Management (syllabus topic)

A thread is a lightweight unit of execution inside a process: it shares code, data and files with sibling threads but owns a PC, register set and stack. User-level threads are managed by a library (fast switches, but one blocking call blocks the whole process); kernel-level threads are scheduled by the OS (can use multiple CPUs, slower switches). Java's Thread and POSIX pthread are kernel-supported; context switching between threads of the same process avoids address-space changes.


4. Exam-Ready Question Bank (BCS401 Unit 3)

PYQ-style short answers (2 marks each)

  1. Define a process state. Current activity of a process (new/ready/running/waiting/terminated) stored in the PCB.
  2. Name one piece of process identification information. PID (also: parent PID or user ID).
  3. List three PCB components. PID, program counter, CPU registers / process state / memory limits.
  4. Purpose of a page replacement algorithm? (Unit 4 overlap) choose a victim frame to minimise future page faults.

Long-answer prompts with model outlines

Prompt (source) Model outline
Process concept + states + diagram (2024-25, 7m) Definition → 5 states → diagram → 6 transitions
What is a PCB + role (2025-26, 7m) Definition → 8 field groups → context-switch role
Structure/contents of PCB (2023-24, 7m) Same table + creation/deletion lifecycle
Deadlock concept, prevention, avoidance (2023-24, 7m) Definition → 4 conditions → prevention table → avoidance vs. prevention
Prevention/avoidance/detection/recovery (2023-24, 7m) Four-row strategy table + trade-off line
Context-switch actions (predicted, 7m) 7 numbered kernel steps
Banker's snapshot (predicted, 7m) Need matrix → safety table → tentative request table
Tape drives (predicted, 7m) Need column → available → safe sequence → option 2
SJF / priority Gantt charts (predicted, 7m each) Event table → chart → completion/TAT/WT table → averages

Practice questions (label: practice, not real PYQs)

  1. Practice: For FCFS with P1(0,8), P2(1,6), P3(2,9), P4(3,3), compute waiting times and show the convoy effect.
  2. Practice: For the same data compute non-preemptive SJF and compare its average waiting time with the 8.2 ms obtained for SRTF.
  3. Practice: A system has 4 resources and 3 processes with max needs 2, 3, 4 and current allocations 1, 1, 1. Determine whether it is safe.
  4. Practice: Explain how aging prevents starvation in priority scheduling.
  5. Practice: Show why a cycle in a resource-allocation graph with two instances of a resource type does not necessarily imply deadlock.

5. Last-Night Survival Checklist (Unit 3 only)

  1. Formula trio: TAT = completion − arrival; WT = TAT − burst; RT = first-run − arrival. Write them at the top of the answer sheet.
  2. Two Gantt charts memorised: SRTF example → avg WT 8.2 ms, avg TAT 14.2 ms; preemptive priority example → avg WT 29.0 ms.
  3. Banker's algorithm order: Need matrix → Request ≤ Need → Request ≤ Available → tentative state → safety sequence → grant/deny.
  4. Deadlock: four Coffman conditions with one prevention method each; four handling strategies with trade-offs.
  5. PCB: eight fields, especially PID; context switch = save old → schedule → load new → resume.

Final scheduling reminder: In a 7-mark numerical, the Gantt chart earns marks by itself; the table of completion/TAT/waiting times earns the rest. Never answer with only the final average, and never forget to state that priority 0 is highest in the given question.