🖥️ Operating Systems Notes

- [📌 How to use these notes](#how)
- [🗺️ Roadmap](#roadmap)
- [🧭 Phase 0 · Foundations from Zero](#phase-0)
  - [✅0.1.1 Inside a computer: CPU, memory, disk, I/O; bits, bytes and powers of two](#l-0-1-1)
  - [✅0.1.2 What an operating system does: kernel, user mode and kernel mode, interrupts](#l-0-1-2)
  - [✅0.1.3 System calls: how programs ask the operating system for help](#l-0-1-3)
  - [✅LI-0.1 Chapter 0.1 Lock-in](#l-LI-0-1)
  - [✅CP-0 Phase 0 Checkpoint (15 questions)](#l-CP-0)
- [⚙️ Phase 1 · Processes & Threads](#phase-1)
  - [✅1.1.1 Processes: memory layout, process control block and process states](#l-1-1-1)
  - [✅1.1.2 Creating processes with fork(), exec() and wait(); context switches and schedulers](#l-1-1-2)
  - [✅LI-1.1 Chapter 1.1 Lock-in](#l-LI-1-1)
  - [✅1.2.1 Threads: what they share, user-level vs kernel-level threads](#l-1-2-1)
  - [✅1.2.2 Inter-process communication: shared memory, message passing and pipes](#l-1-2-2)
  - [✅LI-1.2 Chapter 1.2 Lock-in](#l-LI-1-2)
  - [✅CP-1 Phase 1 Checkpoint (15 questions)](#l-CP-1)
- [⏱️ Phase 2 · CPU Scheduling](#phase-2)
  - [✅2.1.1 Scheduling basics: the times we measure; first-come first-served](#l-2-1-1)
  - [✅2.1.2 Shortest job first and shortest remaining time first](#l-2-1-2)
  - [✅2.1.3 Priority scheduling, starvation and aging; highest response ratio next](#l-2-1-3)
  - [✅LI-2.1 Chapter 2.1 Lock-in](#l-LI-2-1)
  - [✅2.2.1 Round robin and the time quantum](#l-2-2-1)
  - [✅2.2.2 Multilevel queues, CPU and I/O bursts, CPU utilisation](#l-2-2-2)
  - [✅LI-2.2 Chapter 2.2 Lock-in](#l-LI-2-2)
  - [✅CP-2 Phase 2 Checkpoint (15 questions)](#l-CP-2)
- [🔒 Phase 3 · Concurrency & Synchronization](#phase-3)
  - [✅3.1.1 Race conditions and the critical-section problem](#l-3-1-1)
  - [✅3.1.2 Software solutions: turn and flag attempts, Peterson's algorithm](#l-3-1-2)
  - [✅3.1.3 Hardware help: test-and-set, compare-and-swap, spinlocks](#l-3-1-3)
  - [✅LI-3.1 Chapter 3.1 Lock-in](#l-LI-3-1)
  - [✅3.2.1 Semaphores: wait, signal, counting and binary semaphores](#l-3-2-1)
  - [✅3.2.2 Classic problems: bounded buffer, readers–writers, dining philosophers](#l-3-2-2)
  - [✅3.2.3 Monitors, and reasoning about concurrent code](#l-3-2-3)
  - [✅LI-3.2 Chapter 3.2 Lock-in](#l-LI-3-2)
  - [✅CP-3 Phase 3 Checkpoint (15 questions)](#l-CP-3)
- [🧱 Phase 4 · Deadlock](#phase-4)
  - [✅4.1.1 Deadlock: the four conditions and resource-allocation graphs](#l-4-1-1)
  - [✅4.1.2 Prevention and avoidance: safe states and the banker's algorithm](#l-4-1-2)
  - [✅4.1.3 Detection, recovery, and the minimum-resources formula](#l-4-1-3)
  - [✅LI-4.1 Chapter 4.1 Lock-in](#l-LI-4-1)
  - [✅CP-4 Phase 4 Checkpoint (15 questions)](#l-CP-4)
- [🧠 Phase 5 · Memory Management & Virtual Memory](#phase-5)
  - [✅5.1.1 Addresses and contiguous allocation: fits and fragmentation](#l-5-1-1)
  - [✅5.2.1 Paging: pages, frames, page tables and the address split](#l-5-2-1)
  - [✅5.2.2 TLBs, effective access time and multilevel page tables](#l-5-2-2)
  - [✅5.2.3 Segmentation, and segmentation with paging](#l-5-2-3)
  - [✅LI-5.1-5.2 Chapters 5.1–5.2 Lock-in](#l-LI-5-1-5-2)
  - [✅5.3.1 Demand paging, page faults and effective access time](#l-5-3-1)
  - [✅5.3.2 Page replacement: FIFO, optimal and LRU; Belady's anomaly](#l-5-3-2)
  - [✅5.3.3 Frame allocation, thrashing, working sets and the clock algorithm](#l-5-3-3)
  - [✅LI-5.3 Chapter 5.3 Lock-in](#l-LI-5-3)
  - [✅CP-5 Phase 5 Checkpoint (15 questions)](#l-CP-5)
- [💾 Phase 6 · File Systems & I/O](#phase-6)
  - [✅6.1.1 Files, directories and access methods](#l-6-1-1)
  - [✅6.1.2 Allocation methods: contiguous, linked (FAT), indexed (inodes); free space](#l-6-1-2)
  - [✅LI-6.1 Chapter 6.1 Lock-in](#l-LI-6-1)
  - [✅6.2.1 Disk structure and access time](#l-6-2-1)
  - [✅6.2.2 Disk scheduling: FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK](#l-6-2-2)
  - [✅6.2.3 I/O techniques: programmed I/O, interrupts, DMA, buffering and spooling](#l-6-2-3)
  - [✅LI-6.2 Chapter 6.2 Lock-in](#l-LI-6-2)
  - [✅CP-6 Phase 6 Checkpoint (15 questions)](#l-CP-6)
- [🏁 Phase 7 · Integration & Final Test](#phase-7)
  - [✅7.1.1 Master Rule Sheet (all rule cards merged)](#l-7-1-1)
  - [✅7.2.1 Mixed practice set 1](#l-7-2-1)
  - [✅7.2.2 Mixed practice set 2](#l-7-2-2)
  - [✅7.2.3 Mixed practice set 3](#l-7-2-3)
  - [✅7.3.1 GATE pattern drill: recurring patterns and fastest methods](#l-7-3-1)
  - [✅7.4.1 Final end-to-end test (30 questions, 90 min)](#l-7-4-1)
- [🔑 Final test key](#final-key)

🖥️

# GATE 2027 · Operating Systems — Complete Notes

SyllabusGATE 2027 CS · Section 8 Operating System (IIT Madras)

Roadmap58 items · 33 lessons · 8 phases

Built58 / 58 items ready · 440 practice questions

Verified551 answers re-computed by code (fork counts, scheduling Gantt charts, waiting and turnaround times, interleavings, semaphore values, banker's safety checks, address splits, page-table sizes, effective access times, page-fault counts, disk head movements, file-size limits) · all passing

Your progress0 / 58 marked done

## How to use these notes

🎯

These notes take you from **absolute zero** to full marks in GATE Operating Systems. Phase 0 starts with what a CPU, memory and a disk are, so nothing is assumed. Read in order: every lesson uses only ideas taught before it. Each lesson takes 35–55 minutes. Every lesson has the same sections. Questions always come before answers. Answers sit in a closed **Answer Vault** at the bottom of each lesson; the Predict First answer opens Section 3.

🗣️

**Super-easy promise.** Every Core Concept begins with an **In plain words** box: the whole idea in everyday language (a kitchen, a queue at a counter, a shared notebook) before any jargon. New terms are explained the first time they appear.

🧪

**Verified.** Computable answers were re-computed by code before they were written down: fork counts, Gantt charts, waiting times, interleavings, semaphore values, banker's checks, address splits, page-table sizes, access times, page faults, disk head movement and file-size limits.

🔁

Spaced recall

Each lesson opens with 3 warm-up questions on earlier lessons: usually one from the lesson just before and the others from further back, so older ideas keep coming back. Answer them in your head first.

### Your commands, on this page

| Command | Here |
| --- | --- |
| **next** | The “Type next →” link at the end of every lesson. |
| **roadmap** | The roadmap below and the sidebar. Press **Mark as done** on a lesson and it gets a ✅ in both (stored in this browser). |
| **revise \[lesson ID\]** | Search the sidebar for the ID, or use that lesson's Rule Card and the Master Rule Sheet (7.1.1). |
| **simpler / deeper** | Ask Claude in chat, naming the lesson ID. Deeper practice for every chapter is in its Lock-in and in Phase 7. |
| **start final test** | Lesson 7.4.1. The test page shows no answers. |
| **submit** | Enter your answers in 7.4.1 and press **Submit answers**: score with GATE negative marking, topic-wise accuracy, the questions you got wrong and the lessons to re-read. |
| **key** | The very last section of the notes. |

### Conventions used throughout

📐

- **Sizes**: 1 KB = 2¹⁰ bytes, 1 MB = 2²⁰, 1 GB = 2³⁰ (memory is counted in powers of two). Memory is byte-addressable unless a question says otherwise.
- **Running examples**: scheduling lessons reuse one set of processes P1–P5; page-replacement lessons reuse the reference string 7 0 1 2 0 3 0 4 2 3 0 3 2; disk lessons reuse the request queue 98, 183, 37, 122, 14, 124, 65, 67 with the head at 53.
- **Scheduling ties**: when two processes are equally good, the one that arrived first (then the lower number) goes first. In round robin, a process that arrives at the same instant as another is pre-empted joins the ready queue **before** the pre-empted one.
- **Times** are in milliseconds unless stated; context-switch time is 0 unless a question gives it.
- **Code** is C-like pseudocode; `fork()` returns 0 in the child.
- **Marks** follow GATE: MCQ wrong answers cost 1/3 (1-mark) or 2/3 (2-mark); MSQ and NAT have no negative marking; MSQ has no partial credit.

## Roadmap

Lesson IDs are Phase.Chapter.Topic, for example 5.3.2 is Phase 5, Chapter 5.3, Topic 2. The order is a prerequisite chain. ✅ marks what you have marked as done.

🧭 **PHASE 0 — FOUNDATIONS FROM ZERO**

- Ch 0.1 What an operating system does
- ✅[0.1.1 Inside a computer: CPU, memory, disk, I/O; bits, bytes and powers of two](#l-0-1-1)
- ✅[0.1.2 What an operating system does: kernel, user mode and kernel mode, interrupts](#l-0-1-2)
- ✅[0.1.3 System calls: how programs ask the operating system for help](#l-0-1-3)
- ✅[LI-0.1 Chapter 0.1 Lock-in](#l-LI-0-1) Lock-in
- ✅[CP-0 Phase 0 Checkpoint (15 questions)](#l-CP-0) Checkpoint

⚙️ **PHASE 1 — PROCESSES & THREADS**

- Ch 1.1 Processes
- ✅[1.1.1 Processes: memory layout, process control block and process states](#l-1-1-1) GATE favourite
- ✅[1.1.2 Creating processes with fork(), exec() and wait(); context switches and schedulers](#l-1-1-2) GATE favourite
- ✅[LI-1.1 Chapter 1.1 Lock-in](#l-LI-1-1) Lock-in
- Ch 1.2 Threads and IPC
- ✅[1.2.1 Threads: what they share, user-level vs kernel-level threads](#l-1-2-1)
- ✅[1.2.2 Inter-process communication: shared memory, message passing and pipes](#l-1-2-2)
- ✅[LI-1.2 Chapter 1.2 Lock-in](#l-LI-1-2) Lock-in
- ✅[CP-1 Phase 1 Checkpoint (15 questions)](#l-CP-1) Checkpoint

⏱️ **PHASE 2 — CPU SCHEDULING**

- Ch 2.1 Basic scheduling algorithms
- ✅[2.1.1 Scheduling basics: the times we measure; first-come first-served](#l-2-1-1) GATE favourite
- ✅[2.1.2 Shortest job first and shortest remaining time first](#l-2-1-2) GATE favourite
- ✅[2.1.3 Priority scheduling, starvation and aging; highest response ratio next](#l-2-1-3) GATE favourite
- ✅[LI-2.1 Chapter 2.1 Lock-in](#l-LI-2-1) Lock-in
- Ch 2.2 Time sharing and beyond
- ✅[2.2.1 Round robin and the time quantum](#l-2-2-1) GATE favourite
- ✅[2.2.2 Multilevel queues, CPU and I/O bursts, CPU utilisation](#l-2-2-2)
- ✅[LI-2.2 Chapter 2.2 Lock-in](#l-LI-2-2) Lock-in
- ✅[CP-2 Phase 2 Checkpoint (15 questions)](#l-CP-2) Checkpoint

🔒 **PHASE 3 — CONCURRENCY & SYNCHRONIZATION**

- Ch 3.1 The critical-section problem
- ✅[3.1.1 Race conditions and the critical-section problem](#l-3-1-1) GATE favourite
- ✅[3.1.2 Software solutions: turn and flag attempts, Peterson's algorithm](#l-3-1-2) GATE favourite
- ✅[3.1.3 Hardware help: test-and-set, compare-and-swap, spinlocks](#l-3-1-3)
- ✅[LI-3.1 Chapter 3.1 Lock-in](#l-LI-3-1) Lock-in
- Ch 3.2 Semaphores and classic problems
- ✅[3.2.1 Semaphores: wait, signal, counting and binary semaphores](#l-3-2-1) GATE favourite
- ✅[3.2.2 Classic problems: bounded buffer, readers–writers, dining philosophers](#l-3-2-2) GATE favourite
- ✅[3.2.3 Monitors, and reasoning about concurrent code](#l-3-2-3)
- ✅[LI-3.2 Chapter 3.2 Lock-in](#l-LI-3-2) Lock-in
- ✅[CP-3 Phase 3 Checkpoint (15 questions)](#l-CP-3) Checkpoint

🧱 **PHASE 4 — DEADLOCK**

- Ch 4.1 Deadlock
- ✅[4.1.1 Deadlock: the four conditions and resource-allocation graphs](#l-4-1-1) GATE favourite
- ✅[4.1.2 Prevention and avoidance: safe states and the banker's algorithm](#l-4-1-2) GATE favourite
- ✅[4.1.3 Detection, recovery, and the minimum-resources formula](#l-4-1-3) GATE favourite
- ✅[LI-4.1 Chapter 4.1 Lock-in](#l-LI-4-1) Lock-in
- ✅[CP-4 Phase 4 Checkpoint (15 questions)](#l-CP-4) Checkpoint

🧠 **PHASE 5 — MEMORY MANAGEMENT & VIRTUAL MEMORY**

- Ch 5.1 Contiguous allocation
- ✅[5.1.1 Addresses and contiguous allocation: fits and fragmentation](#l-5-1-1)
- Ch 5.2 Paging
- ✅[5.2.1 Paging: pages, frames, page tables and the address split](#l-5-2-1) GATE favourite
- ✅[5.2.2 TLBs, effective access time and multilevel page tables](#l-5-2-2) GATE favourite
- ✅[5.2.3 Segmentation, and segmentation with paging](#l-5-2-3)
- ✅[LI-5.1-5.2 Chapters 5.1–5.2 Lock-in](#l-LI-5-1-5-2) Lock-in
- Ch 5.3 Virtual memory
- ✅[5.3.1 Demand paging, page faults and effective access time](#l-5-3-1) GATE favourite
- ✅[5.3.2 Page replacement: FIFO, optimal and LRU; Belady's anomaly](#l-5-3-2) GATE favourite
- ✅[5.3.3 Frame allocation, thrashing, working sets and the clock algorithm](#l-5-3-3)
- ✅[LI-5.3 Chapter 5.3 Lock-in](#l-LI-5-3) Lock-in
- ✅[CP-5 Phase 5 Checkpoint (15 questions)](#l-CP-5) Checkpoint

💾 **PHASE 6 — FILE SYSTEMS & I/O**

- Ch 6.1 File systems
- ✅[6.1.1 Files, directories and access methods](#l-6-1-1)
- ✅[6.1.2 Allocation methods: contiguous, linked (FAT), indexed (inodes); free space](#l-6-1-2) GATE favourite
- ✅[LI-6.1 Chapter 6.1 Lock-in](#l-LI-6-1) Lock-in
- Ch 6.2 Disks and I/O
- ✅[6.2.1 Disk structure and access time](#l-6-2-1)
- ✅[6.2.2 Disk scheduling: FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK](#l-6-2-2) GATE favourite
- ✅[6.2.3 I/O techniques: programmed I/O, interrupts, DMA, buffering and spooling](#l-6-2-3)
- ✅[LI-6.2 Chapter 6.2 Lock-in](#l-LI-6-2) Lock-in
- ✅[CP-6 Phase 6 Checkpoint (15 questions)](#l-CP-6) Checkpoint

🏁 **PHASE 7 — INTEGRATION & FINAL TEST**

- Ch 7.1 Master rule sheet
- ✅[7.1.1 Master Rule Sheet (all rule cards merged)](#l-7-1-1) Revision
- Ch 7.2 Mixed practice
- ✅[7.2.1 Mixed practice set 1](#l-7-2-1) Revision
- ✅[7.2.2 Mixed practice set 2](#l-7-2-2) Revision
- ✅[7.2.3 Mixed practice set 3](#l-7-2-3) Revision
- Ch 7.3 GATE pattern drill
- ✅[7.3.1 GATE pattern drill: recurring patterns and fastest methods](#l-7-3-1) Revision
- Ch 7.4 Final test
- ✅[7.4.1 Final end-to-end test (30 questions, 90 min)](#l-7-4-1) Final test

### Phases

[🧭 Phase 0 · Foundations from Zero 3 lessons · 1 lock-ins · checkpoint](#phase-0) [⚙️ Phase 1 · Processes & Threads 4 lessons · 2 lock-ins · checkpoint](#phase-1) [⏱️ Phase 2 · CPU Scheduling 5 lessons · 2 lock-ins · checkpoint](#phase-2) [🔒 Phase 3 · Concurrency & Synchronization 6 lessons · 2 lock-ins · checkpoint](#phase-3) [🧱 Phase 4 · Deadlock 3 lessons · 1 lock-ins · checkpoint](#phase-4) [🧠 Phase 5 · Memory Management & Virtual Memory 7 lessons · 2 lock-ins · checkpoint](#phase-5) [💾 Phase 6 · File Systems & I/O 5 lessons · 2 lock-ins · checkpoint](#phase-6) [🏁 Phase 7 · Integration & Final Test rule sheet · 3 practice sets · drill · final test](#phase-7)

# 🧭Phase 0 — Foundations from Zero

## 📄Lesson 0.1.1 — Inside a computer: CPU, memory, disk, I/O; bits, bytes and powers of two

Phase 0 › Foundations from Zero › Chapter 0.1 What an operating system does › Topic 0.1.1

Phase 0Ch 0.1 What an operating system doesTopic 0.1.1GATE weight: Prerequisite≈ 30 min

### 1The Hook

🎣

Every app you open, from a browser to a game, competes for the same few things: the processor, the memory, the disk and the screen. The **operating system** (OS) is the referee that shares them out. Before we can understand the referee we need to know the players, and the units they are measured in (bytes and powers of two), because half of GATE OS questions are arithmetic on those units.

### 2Predict First

🤔

A memory has addresses written with 10 bits (each bit is 0 or 1). How many different addresses are there?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

Each bit doubles the choices: 2 × 2 × … (10 times) = 2¹⁰ = **1024** addresses.

🗣️

In plain words

A computer has a **CPU** (the worker who follows instructions), **memory** or RAM (the desk where the current work is laid out, fast but forgotten when power goes off), a **disk** (the cupboard: big, slow, permanent) and **I/O devices** (keyboard, screen, network). Everything is stored as bits, and sizes come in powers of two.

#### 1. The four parts

| Part | Job | Everyday picture |
| --- | --- | --- |
| **CPU** (processor) | executes instructions one after another, very fast | the cook |
| **Main memory (RAM)** | holds the programs and data being used now; loses everything at power-off | the kitchen counter |
| **Disk / SSD** | stores files permanently; thousands of times slower than RAM | the store-room |
| **I/O devices** | keyboard, screen, network card, printer | the waiters and the doorbell |

Speed order (fastest first): CPU registers → cache → RAM → SSD → hard disk.

#### 2. Program vs process

A **program** is a file on disk (a recipe). A **process** is a program **while it is running** (a cook actually following the recipe, with ingredients on the counter). One program can be running as several processes at once (two browser windows).

#### 3. Bits, bytes and powers of two

- A **bit** is 0 or 1. A **byte** = 8 bits.
- With **n bits** you can write **2ⁿ** different patterns. 8 bits → 256 values.
- Sizes (memory is counted in powers of two):

| Name | Bytes |
| --- | --- |
| 1 KB (kilobyte) | 2¹⁰ = 1024 |
| 1 MB | 2²⁰ |
| 1 GB | 2³⁰ |
| 1 TB | 2⁴⁰ |

#### 4. Addresses

Memory is a long row of numbered boxes, each holding one byte (**byte-addressable**). The box number is its **address**.

- **n address bits → 2ⁿ addresses → 2ⁿ bytes** of memory.
- A memory of **2ⁿ bytes needs n address bits**: 64 KB = 2⁶ × 2¹⁰ = 2¹⁶ → **16 bits**.
- 32-bit addresses → 2³² bytes = **4 GB**.

#### 5. Handy power-of-two arithmetic

Multiply by adding exponents, divide by subtracting: 4 GB / 4 KB = 2³² / 2¹² = 2²⁰ (about a million). You will do this constantly in memory management (Phase 5).

### 4Visual

The CPU works on what is in RAM; RAM is filled from the disk; I/O devices bring data in and out.

| Address bits | Number of bytes |
| --- | --- |
| 10 | 2¹⁰ = 1 KB |
| 16 | 2¹⁶ = 64 KB |
| 20 | 2²⁰ = 1 MB |
| 32 | 2³² = 4 GB |

### 5Worked Examples

Example 1 Easy

How many bytes are in 8 KB?

Solution

8 × 1024 = **8192** = 2¹³.

Example 2 Medium

How many address bits are needed for a 256 MB byte-addressable memory?

Solution

256 MB = 2⁸ × 2²⁰ = 2²⁸ → **28 bits**.

Example 3 GATE

A 4 GB memory is cut into 4 KB pieces. How many pieces?

Solution

2³²/2¹² = 2²⁰ = **1,048,576**.

### 6GATE Traps

⚠️

- KB here means 2¹⁰ = 1024 bytes, not 1000.
- Byte = 8 bits; don't mix bits and bytes in a size question.
- n address bits give 2ⁿ addresses, not 2n.
- A program is passive (a file); a process is active (running).

### 7Memory Hook

🧠

**"n bits, 2ⁿ choices. Divide powers of two by subtracting exponents."**

### 8Connect the Dots

You know the players. Next lesson introduces the referee: what the **operating system** does, and the special protected mode it runs in.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**NAT1 markAddress bits

How many address bits does a 64 KB byte-addressable memory need?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT1 markPowers of two

How many 4 KB pieces fit in 64 MB?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT2 marksMemory size

A machine has 36-bit addresses (byte-addressable). How many GB of memory can it address?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**MCQ1 markProgram vs process

Which statement is correct?

1. (A) One program can never have two processes.
2. (B) A program is a running process.
3. (C) A process is a program in execution.
4. (D) A process is stored on disk.

**Q5**MCQ1 markSpeed order

Which list is ordered from fastest to slowest?

1. (A) RAM, registers, disk, cache
2. (B) cache, disk, RAM, registers
3. (C) disk, RAM, cache, registers
4. (D) registers, cache, RAM, disk

### 10Rule Card

- CPU executes, RAM holds current work (volatile), disk stores permanently, I/O connects the outside.
- Program = file; process = program in execution.
- Byte = 8 bits; n bits → 2ⁿ values; 1 KB = 2¹⁰, 1 MB = 2²⁰, 1 GB = 2³⁰.
- 2ⁿ bytes ↔ n address bits; divide powers of two by subtracting exponents.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

CPUmain memory (RAM)diskI/O devicesmemory hierarchyprogram vs processbit and bytepowers of twoKB, MB, GBbyte-addressable memoryaddress bits

### 12Answer Vault

🔐 Open the Answer Vault

#### Self-Test

**Q1** Answer: 161 mark

2⁶ × 2¹⁰ = 2¹⁶.

Re-read: [Lesson 0.1.1](#l-0-1-1) — Inside a computer: CPU, memory, disk, I/O; bits, bytes and powers of two

**Q2** Answer: 163841 mark

2²⁶/2¹² = 2¹⁴.

Re-read: [Lesson 0.1.1](#l-0-1-1) — Inside a computer: CPU, memory, disk, I/O; bits, bytes and powers of two

**Q3** Answer: 642 marks

2³⁶/2³⁰ = 2⁶.

Re-read: [Lesson 0.1.1](#l-0-1-1) — Inside a computer: CPU, memory, disk, I/O; bits, bytes and powers of two

**Q4** Answer: (C)1 mark

Running = process.

- **(A) is wrong:** Two browser windows are two processes.
- **(B) is wrong:** Reversed.
- **(D) is wrong:** Programs are stored; processes run in memory.

Re-read: [Lesson 0.1.1](#l-0-1-1) — Inside a computer: CPU, memory, disk, I/O; bits, bytes and powers of two

**Q5** Answer: (D)1 mark

Closest to the CPU is fastest.

- **(A) is wrong:** Registers are fastest.
- **(B) is wrong:** Disk is slowest.
- **(C) is wrong:** Reversed.

Re-read: [Lesson 0.1.1](#l-0-1-1) — Inside a computer: CPU, memory, disk, I/O; bits, bytes and powers of two

Type next → [**0.1.2** What an operating system does: kernel, user mode and kernel mode, interrupts](#l-0-1-2)

## 📄Lesson 0.1.2 — What an operating system does: kernel, user mode and kernel mode, interrupts

Phase 0 › Foundations from Zero › Chapter 0.1 What an operating system does › Topic 0.1.2

Phase 0Ch 0.1 What an operating system doesTopic 0.1.2GATE weight: Prerequisite≈ 35 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. 32 address bits give how much memory? from [Lesson 0.1.1](#l-0-1-1)
2. Program vs process? from [Lesson 0.1.1](#l-0-1-1)

### 1The Hook

🎣

If any program could switch off the timer, overwrite another program's memory or talk to the disk directly, one buggy app could crash the whole machine. So the CPU has two modes: a powerful **kernel mode** reserved for the operating system and a restricted **user mode** for everything else. GATE asks which instructions must be restricted, and how control moves between the two.

### 2Predict First

🤔

Which of these should an ordinary app NOT be allowed to do directly: (a) add two numbers, (b) switch off interrupts, (c) read the current time, (d) change the timer?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

**(b) and (d).** Switching off interrupts or changing the timer would let one app take over the CPU forever. Adding numbers and reading the time are harmless.

🗣️

In plain words

The operating system is the manager that shares the computer between programs and protects them from each other. The CPU has a switch: in **kernel mode** anything goes, in **user mode** dangerous instructions are blocked. Programs run in user mode; the OS kernel runs in kernel mode. **Interrupts** are the doorbell that hands control back to the OS.

#### 1. What an operating system does

- **Resource manager**: shares the CPU, memory, disk and devices among processes.
- **Abstraction**: gives programs simple ideas (files, processes, virtual memory) instead of raw hardware.
- **Protection**: keeps processes from damaging each other or the OS.

The core part that is always in memory and runs in kernel mode is the **kernel**.

#### 2. Two modes

A **mode bit** in the CPU says which mode is active.

- **User mode**: ordinary programs; privileged instructions are refused (attempting one causes a trap to the OS).
- **Kernel mode** (supervisor mode): the OS; every instruction is allowed.
- **Privileged instructions** (kernel mode only): I/O instructions, setting the timer, enabling/disabling interrupts, changing memory-management registers, halting the CPU, switching to kernel mode directly.
- **Not privileged**: arithmetic, reading the clock, and the special **trap / system-call instruction** that *asks* the OS for help (it must be usable from user mode, otherwise programs could never request anything).

#### 3. Interrupts, traps and the timer

- **Interrupt** (from hardware): a device signals the CPU ("key pressed", "disk read finished"). The CPU saves what it was doing, switches to kernel mode and runs the OS's **interrupt handler**.
- **Trap / exception** (from software): caused by the running program: a system call, a division by zero, an illegal memory access.
- **Timer interrupt**: the OS sets a timer before giving the CPU to a process; when it fires, the OS gets control back. This is how one process is prevented from hogging the CPU.

#### 4. Kinds of operating systems

| Kind | Idea |
| --- | --- |
| Batch | jobs run one after another, no interaction |
| **Multiprogramming** | several programs in memory; when one waits for I/O, the CPU runs another (keeps the CPU busy) |
| **Time-sharing** (multitasking) | switch between programs so quickly that each user feels it has the machine |
| Real-time | must meet deadlines (hard or soft) |

The **degree of multiprogramming** is the number of processes in memory at once.

### 4Visual

Control enters the kernel only through traps (system calls, errors) and interrupts; the kernel returns to user mode when done.

| Instruction | Privileged? |
| --- | --- |
| set the timer | yes |
| disable interrupts | yes |
| perform I/O directly | yes |
| change page-table / memory registers | yes |
| read the time of day | no |
| add, compare, jump | no |
| system-call (trap) instruction | no (it is how user programs enter the kernel) |

### 5Worked Examples

Example 1 Easy

In which mode does a word processor normally run?

Solution

**User mode.**

Example 2 Medium

Why must the "set timer" instruction be privileged?

Solution

A user program could otherwise set a huge timer (or none) and **never give the CPU back**.

Example 3 GATE

Which instruction must be executable in user mode: "disable interrupts" or "trap to the kernel"?

Solution

**Trap to the kernel**: it is the only way a user program can ask for OS services.

### 6GATE Traps

⚠️

- The system-call (trap) instruction is **not** privileged, even though it leads into the kernel.
- Reading the clock is harmless; **setting** the timer is privileged.
- Interrupts come from devices; traps come from the running program.
- Multiprogramming ≠ multiprocessing (the latter means several CPUs).

### 7Memory Hook

🧠

**"Dangerous instructions live in kernel mode; apps knock with a trap."**

### 8Connect the Dots

A user program that needs a file or a new process must ask the kernel. The next lesson shows exactly how: **system calls**.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**MCQ1 markPrivileged instructions

Which instruction should be privileged?

1. (A) Set the value of the timer
2. (B) Add two registers
3. (C) Read the time of day
4. (D) Execute a system-call (trap) instruction

**Q2**MSQ2 marksPrivileged set

Which of these must run only in kernel mode?

1. (A) Read the system clock
2. (B) Directly start a disk I/O operation
3. (C) Change the memory-management (page-table) register
4. (D) Disable all interrupts

**Q3**MCQ1 markInterrupts

A keyboard key press reaches the OS as:

1. (A) a system call
2. (B) a hardware interrupt
3. (C) a trap
4. (D) a privileged instruction

**Q4**MCQ1 markTimer

What lets the OS take the CPU back from a process that never makes a system call?

1. (A) Virtual memory
2. (B) The disk controller
3. (C) The mode bit
4. (D) The timer interrupt

**Q5**MCQ1 markMultiprogramming

The main goal of multiprogramming is to:

1. (A) keep the CPU busy while other programs wait for I/O
2. (B) give each user a separate CPU
3. (C) run real-time tasks
4. (D) remove the need for an OS

### 10Rule Card

- OS = resource manager + abstraction + protection; kernel runs in kernel mode.
- Mode bit: user mode (restricted) vs kernel mode (all instructions).
- Privileged: I/O, set timer, enable/disable interrupts, memory-management registers, halt. Not privileged: arithmetic, read clock, trap/system-call instruction.
- Interrupt = from hardware; trap/exception = from the running program; timer interrupt returns control to the OS.
- Multiprogramming keeps the CPU busy; time-sharing switches fast for interaction.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

operating system roleskerneluser mode and kernel modemode bitprivileged instructionshardware interruptstraps and exceptionsinterrupt handlertimer interruptbatch, multiprogramming, time-sharing and real-time systemsdegree of multiprogramming

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. 4 GB.
2. A process is a program in execution.

#### Self-Test

**Q1** Answer: (A)1 mark

Otherwise a process could keep the CPU forever.

- **(B) is wrong:** Ordinary arithmetic.
- **(C) is wrong:** Harmless.
- **(D) is wrong:** User programs need it to request services.

Re-read: [Lesson 0.1.2](#l-0-1-2) — What an operating system does: kernel, user mode and kernel mode, interrupts

**Q2** Answer: (B) (C) (D)2 marks

Reading the clock cannot harm others.

- **(A) is wrong:** Not privileged.

Re-read: [Lesson 0.1.2](#l-0-1-2) — What an operating system does: kernel, user mode and kernel mode, interrupts

**Q3** Answer: (B)1 mark

Generated by a device.

- **(A) is wrong:** The program did not ask.
- **(C) is wrong:** Traps come from the running program.
- **(D) is wrong:** Not an instruction.

Re-read: [Lesson 0.1.2](#l-0-1-2) — What an operating system does: kernel, user mode and kernel mode, interrupts

**Q4** Answer: (D)1 mark

The timer fires and enters the kernel.

- **(A) is wrong:** About memory.
- **(B) is wrong:** Unrelated.
- **(C) is wrong:** Only says which mode is active.

Re-read: [Lesson 0.1.2](#l-0-1-2) — What an operating system does: kernel, user mode and kernel mode, interrupts

**Q5** Answer: (A)1 mark

Overlap computing with I/O waits.

- **(B) is wrong:** That is multiprocessing.
- **(C) is wrong:** Real-time is a different goal.
- **(D) is wrong:** It needs an OS.

Re-read: [Lesson 0.1.2](#l-0-1-2) — What an operating system does: kernel, user mode and kernel mode, interrupts

Type next → [**0.1.3** System calls: how programs ask the operating system for help](#l-0-1-3)

## 📄Lesson 0.1.3 — System calls: how programs ask the operating system for help

Phase 0 › Foundations from Zero › Chapter 0.1 What an operating system does › Topic 0.1.3

Phase 0Ch 0.1 What an operating system doesTopic 0.1.3GATE weight: Medium≈ 35 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. Is the system-call (trap) instruction privileged? from [Lesson 0.1.2](#l-0-1-2)
2. 2³²/2¹²? from [Lesson 0.1.1](#l-0-1-1)

### 1The Hook

🎣

When a C program calls printf("hi"), the letters eventually reach your screen, but the program never touches the screen itself; it is not allowed to. Somewhere a request crosses from user mode into the kernel. That doorway is a **system call**. GATE asks what happens during one, and which familiar functions are system calls and which are not.

### 2Predict First

🤔

A program calls printf three times, and the C library collects the text and sends it in one go. How many times did the program enter the kernel to print?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

**Once.** printf is a library function that buffers text in user mode; only the single underlying **write** system call enters the kernel.

🗣️

In plain words

A **system call** is a program's request to the operating system: "open this file", "give me more memory", "start a new process". The program puts its request in agreed places, executes a special trap instruction, the CPU jumps into the kernel, the kernel does the work, and control returns with an answer.

#### 1. The steps of a system call

1. The program calls a library wrapper (e.g. `read(fd, buf, n)`).
2. The wrapper puts the **system-call number** and the **parameters** in agreed places.
3. It executes the **trap** instruction: the CPU switches to **kernel mode** and jumps to the OS's trap handler.
4. The kernel looks up the number in the **system-call table**, runs the matching function, and puts the result in a register.
5. The CPU switches back to **user mode** and the program continues.

Each system call therefore costs **two mode switches** (user → kernel → user).

#### 2. Passing parameters

In registers (fast, few); in a block of memory whose address is in a register; or on the stack.

#### 3. Kinds of system calls (UNIX examples)

| Kind | Examples |
| --- | --- |
| Process control | fork, exec, exit, wait, kill |
| File management | open, read, write, close, lseek |
| Device management | ioctl, read/write on devices |
| Information | getpid, time |
| Communication | pipe, shmget, send/recv (sockets) |

#### 4. System calls vs library functions

- **System calls**: fork, exec, read, write, open, close, exit, brk/sbrk.
- **Library functions** (run in user mode, may or may not call the kernel): printf (calls write), malloc (sometimes calls brk/mmap), strlen, sqrt (never calls the kernel).

#### 5. Kernel structures (names to recognise)

- **Monolithic kernel**: all OS services in one big kernel (traditional UNIX, Linux).
- **Microkernel**: only the essentials in the kernel; file systems and drivers run as user-level servers (more switches, more robust).

### 4Visual

```
read(fd, buf, 100) step by step

 USER MODE                          KERNEL MODE
 ---------                          -----------
 program calls read()
   library puts number + params
   in registers, executes TRAP  ---> trap handler
                                     look up syscall table
                                     sys_read(): copy data
                                     result -> register
   program continues            <--- return-from-trap (back to user mode)
```

### 5Worked Examples

Example 1 Easy

Is strlen a system call?

Solution

**No**: it just counts characters in user memory.

Example 2 Medium

How many mode switches does one system call cause?

Solution

**2**: user → kernel, then kernel → user.

Example 3 GATE

A program makes 5 system calls. How many times does the CPU switch from user mode to kernel mode because of them?

Solution

**5** (and 5 switches back).

### 6GATE Traps

⚠️

- printf and malloc are **library** functions; write and brk are the system calls underneath.
- A system call is entered by a **trap** instruction, not an ordinary function call.
- The trap switches **to** kernel mode; the return switches back.
- Not every library call reaches the kernel (sqrt never does).

### 7Memory Hook

🧠

**"Library wraps, trap enters, kernel works, return leaves."**

### 8Connect the Dots

Phase 0 is complete. Phase 1 looks at the most important thing the kernel manages: **processes**, how they are created with the fork system call, and what states they move through.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**MCQ1 markSystem calls

Which of these is a system call?

1. (A) strlen
2. (B) sqrt
3. (C) write
4. (D) printf

**Q2**NAT1 markMode switches

A program performs 7 system calls. Total number of mode switches they cause?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**MCQ1 markMechanism

A system call transfers control to the kernel using:

1. (A) a privileged instruction executed in user mode
2. (B) a trap (software interrupt) instruction
3. (C) disabling interrupts
4. (D) an ordinary function call

**Q4**MSQ2 marksCategories

Which are process-control system calls?

1. (A) exec
2. (B) fork
3. (C) wait
4. (D) lseek

**Q5**MCQ1 markKernel design

In a microkernel, file systems and device drivers usually run:

1. (A) in the BIOS
2. (B) on the disk controller
3. (C) inside the kernel
4. (D) as user-level server processes

### 10Rule Card

- System call: wrapper → parameters + number → trap → kernel handler via system-call table → result → return to user mode (2 mode switches).
- Parameters: registers, memory block, or stack.
- Categories: process (fork, exec, exit, wait), file (open, read, write, close, lseek), device, information, communication.
- printf, malloc, strlen are library functions; write, brk are system calls.
- Monolithic kernel vs microkernel.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

system callsystem-call wrappersystem-call number and tabletrap instructionparameter passingmode switches per system callprocess-control, file, device, information and communication callslibrary function vs system callmonolithic kernelmicrokernel

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. No.
2. 2²⁰.

#### Self-Test

**Q1** Answer: (C)1 mark

It enters the kernel.

- **(A) is wrong:** Pure user-mode code.
- **(B) is wrong:** Pure user-mode code.
- **(D) is wrong:** A library function that calls write.

Re-read: [Lesson 0.1.3](#l-0-1-3) — System calls: how programs ask the operating system for help

**Q2** Answer: 141 mark

2 per call.

Re-read: [Lesson 0.1.3](#l-0-1-3) — System calls: how programs ask the operating system for help

**Q3** Answer: (B)1 mark

The trap switches mode safely.

- **(A) is wrong:** Privileged instructions fail in user mode.
- **(C) is wrong:** Privileged, so a user program can't do it.
- **(D) is wrong:** Ordinary calls stay in user mode.

Re-read: [Lesson 0.1.3](#l-0-1-3) — System calls: how programs ask the operating system for help

**Q4** Answer: (A) (B) (C)2 marks

lseek moves a file position.

- **(D) is wrong:** File management.

Re-read: [Lesson 0.1.3](#l-0-1-3) — System calls: how programs ask the operating system for help

**Q5** Answer: (D)1 mark

Only essentials stay in the kernel.

- **(A) is wrong:** Unrelated.
- **(B) is wrong:** Unrelated.
- **(C) is wrong:** That is a monolithic kernel.

Re-read: [Lesson 0.1.3](#l-0-1-3) — System calls: how programs ask the operating system for help

Type next → [**LI-0.1** Chapter 0.1 Lock-in](#l-LI-0-1)

## 🔒Chapter 0.1 Lock-in — What an operating system does

Phase 0 › Foundations from Zero › Chapter 0.1 What an operating system does

Phase 0Ch 0.1 What an operating system does

### ACompressed recap

🧾

CPU, RAM (volatile), disk (permanent), I/O; program vs process; bits and bytes; KB = 2¹⁰; n address bits ↔ 2ⁿ bytes. OS = resource manager + protection; user vs kernel mode; privileged instructions (I/O, timer, interrupts, memory registers); interrupts vs traps; timer interrupt. System call = trap into kernel and back (2 mode switches); library functions vs system calls.

### BMerged rule card

[0.1.1](#l-0-1-1) Inside a computer: CPU, memory, disk, I/O; bits, bytes and powers of two

- CPU executes, RAM holds current work (volatile), disk stores permanently, I/O connects the outside.
- Program = file; process = program in execution.
- Byte = 8 bits; n bits → 2ⁿ values; 1 KB = 2¹⁰, 1 MB = 2²⁰, 1 GB = 2³⁰.
- 2ⁿ bytes ↔ n address bits; divide powers of two by subtracting exponents.

[0.1.2](#l-0-1-2) What an operating system does: kernel, user mode and kernel mode, interrupts

- OS = resource manager + abstraction + protection; kernel runs in kernel mode.
- Mode bit: user mode (restricted) vs kernel mode (all instructions).
- Privileged: I/O, set timer, enable/disable interrupts, memory-management registers, halt. Not privileged: arithmetic, read clock, trap/system-call instruction.
- Interrupt = from hardware; trap/exception = from the running program; timer interrupt returns control to the OS.
- Multiprogramming keeps the CPU busy; time-sharing switches fast for interaction.

[0.1.3](#l-0-1-3) System calls: how programs ask the operating system for help

- System call: wrapper → parameters + number → trap → kernel handler via system-call table → result → return to user mode (2 mode switches).
- Parameters: registers, memory block, or stack.
- Categories: process (fork, exec, exit, wait), file (open, read, write, close, lseek), device, information, communication.
- printf, malloc, strlen are library functions; write, brk are system calls.
- Monolithic kernel vs microkernel.

### CInterleaved GATE-style questions

**Q1**NAT1 markAddress bits

How many address bits does a 2 GB byte-addressable memory need?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT2 marksDivision

A 1 GB memory is divided into 8 KB blocks. How many blocks?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**MCQ1 markProcess

Two copies of the same text editor are open. How many processes are running the editor?

1. (A) 2
2. (B) 0
3. (C) It depends on the file size
4. (D) 1

**Q4**MCQ1 markPrivilege

Which instruction need NOT be privileged?

1. (A) Halt the processor
2. (B) Load the base/limit memory registers
3. (C) Read the processor clock
4. (D) Disable interrupts

**Q5**MCQ1 markTraps

Division by zero in a user program causes:

1. (A) a hardware interrupt from a device
2. (B) a trap (exception) to the OS
3. (C) a switch to user mode
4. (D) nothing; the result is 0

**Q6**MSQ2 marksModes

Which statements are true?

1. (A) The mode bit records whether the CPU is in user or kernel mode.
2. (B) A timer interrupt lets the OS regain the CPU.
3. (C) User programs may execute I/O instructions directly.
4. (D) The kernel runs in kernel mode.

**Q7**NAT1 markSystem calls

A program calls printf 10 times; the library buffers the text and issues 2 write system calls. How many times does the program enter the kernel for printing?

Numerical answer: \_\_\_\_\_\_\_\_

**Q8**MCQ1 markLibrary vs system call

malloc is best described as:

1. (A) an interrupt handler
2. (B) a library function that may use a system call (brk or mmap) to get more memory
3. (C) a privileged instruction
4. (D) a system call

### DAnswer Vault

🔐 Open the Answer Vault

**Q1** Answer: 311 mark

2 × 2³⁰ = 2³¹.

Re-read: [Lesson 0.1.1](#l-0-1-1) — Inside a computer: CPU, memory, disk, I/O; bits, bytes and powers of two

**Q2** Answer: 1310722 marks

2³⁰/2¹³ = 2¹⁷.

Re-read: [Lesson 0.1.1](#l-0-1-1) — Inside a computer: CPU, memory, disk, I/O; bits, bytes and powers of two

**Q3** Answer: (A)1 mark

Each running copy is a process.

- **(B) is wrong:** They are running.
- **(C) is wrong:** Unrelated.
- **(D) is wrong:** One program, two processes.

Re-read: [Lesson 0.1.1](#l-0-1-1) — Inside a computer: CPU, memory, disk, I/O; bits, bytes and powers of two

**Q4** Answer: (C)1 mark

Reading the clock cannot harm anyone.

- **(A) is wrong:** Would stop everything.
- **(B) is wrong:** Would break memory protection.
- **(D) is wrong:** Could stop the OS from regaining control.

Re-read: [Lesson 0.1.2](#l-0-1-2) — What an operating system does: kernel, user mode and kernel mode, interrupts

**Q5** Answer: (B)1 mark

An error in the running program.

- **(A) is wrong:** No device is involved.
- **(C) is wrong:** It enters kernel mode.
- **(D) is wrong:** The OS must handle it.

Re-read: [Lesson 0.1.2](#l-0-1-2) — What an operating system does: kernel, user mode and kernel mode, interrupts

**Q6** Answer: (A) (B) (D)2 marks

I/O instructions are privileged.

- **(C) is wrong:** They must go through system calls.

Re-read: [Lesson 0.1.2](#l-0-1-2) — What an operating system does: kernel, user mode and kernel mode, interrupts

**Q7** Answer: 21 mark

Only the write calls trap.

Re-read: [Lesson 0.1.3](#l-0-1-3) — System calls: how programs ask the operating system for help

**Q8** Answer: (B)1 mark

Runs in user mode, occasionally asks the kernel.

- **(A) is wrong:** Not a handler.
- **(C) is wrong:** Not an instruction.
- **(D) is wrong:** The system calls are brk/mmap.

Re-read: [Lesson 0.1.3](#l-0-1-3) — System calls: how programs ask the operating system for help

Type next → [**CP-0** Phase 0 Checkpoint (15 questions)](#l-CP-0)

## ⏱️Phase 0 Checkpoint — Foundations from Zero

Phase 0 › Foundations from Zero

Phase 0

Phase 0 Checkpoint: 15 questions on computer basics, modes and system calls.

⏱️

**15 questions · 20 marks · 40 minutes.** Negative marking on MCQ only: −1/3 mark for a wrong 1-mark MCQ, −2/3 for a wrong 2-mark MCQ. No negative marking for MSQ or NAT; MSQ has no partial credit.

**Q1**NAT1 markPowers of two

How many bytes are in 2 MB?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT1 markAddress bits

A byte-addressable memory has 2²⁴ bytes. How many address bits?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT2 marksBlocks

A 16 GB disk is divided into 4 KB blocks. How many blocks (as a power of two, give the exponent)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**MCQ1 markVolatile

Which loses its contents when power is switched off?

1. (A) USB flash drive
2. (B) Hard disk
3. (C) SSD
4. (D) RAM

**Q5**MCQ1 markOS role

Which is NOT a job of the operating system?

1. (A) Protecting processes from each other
2. (B) Managing files on disk
3. (C) Compiling your C program
4. (D) Sharing the CPU among processes

**Q6**MSQ2 marksPrivileged

Which instructions must be privileged?

1. (A) Read a general-purpose register
2. (B) Set the timer
3. (C) Change the page-table base register
4. (D) Enable or disable interrupts

**Q7**MCQ1 markInterrupt vs trap

A disk finishing a read operation signals the CPU with:

1. (A) an interrupt
2. (B) a trap
3. (C) a system call
4. (D) a privileged instruction

**Q8**MCQ1 markMultiprogramming

The degree of multiprogramming is:

1. (A) the number of CPUs
2. (B) the time-slice length
3. (C) the number of users
4. (D) the number of processes in memory at once

**Q9**MCQ1 markReal-time

An airbag controller that must react within 10 ms needs a:

1. (A) hard real-time OS
2. (B) time-sharing OS
3. (C) microkernel only
4. (D) batch OS

**Q10**NAT1 markMode switches

A program makes 12 system calls. How many user-to-kernel switches do they cause?

Numerical answer: \_\_\_\_\_\_\_\_

**Q11**MCQ1 markSystem call

Which is a system call in UNIX?

1. (A) printf
2. (B) strcpy
3. (C) fork
4. (D) atoi

**Q12**MCQ2 marksSteps

During a system call, the kernel finds which routine to run by:

1. (A) asking the user
2. (B) indexing the system-call table with the system-call number
3. (C) reading the disk
4. (D) scanning the program's source code

**Q13**MSQ2 marksParameters

How can a program pass parameters to a system call?

1. (A) In CPU registers
2. (B) In a memory block whose address is in a register
3. (C) On the stack
4. (D) By writing directly into kernel memory

**Q14**MCQ1 markKernel design

Linux is usually described as a:

1. (A) microkernel
2. (B) real-time-only system
3. (C) monolithic kernel
4. (D) batch system

**Q15**NAT2 marksArithmetic

A 32-bit address space is split into pages of 4 KB. How many pages?

Numerical answer: \_\_\_\_\_\_\_\_

### ✓Answer Vault

🔐 Open the Answer Vault

**Q1** Answer: 20971521 mark

2 × 2²⁰.

Re-read: [Lesson 0.1.1](#l-0-1-1) — Inside a computer: CPU, memory, disk, I/O; bits, bytes and powers of two

**Q2** Answer: 241 mark

n bits ↔ 2ⁿ bytes.

Re-read: [Lesson 0.1.1](#l-0-1-1) — Inside a computer: CPU, memory, disk, I/O; bits, bytes and powers of two

**Q3** Answer: 222 marks

2³⁴/2¹² = 2²².

Re-read: [Lesson 0.1.1](#l-0-1-1) — Inside a computer: CPU, memory, disk, I/O; bits, bytes and powers of two

**Q4** Answer: (D)1 mark

Main memory is volatile.

- **(A) is wrong:** Non-volatile.
- **(B) is wrong:** Non-volatile.
- **(C) is wrong:** Non-volatile.

Re-read: [Lesson 0.1.1](#l-0-1-1) — Inside a computer: CPU, memory, disk, I/O; bits, bytes and powers of two

**Q5** Answer: (C)1 mark

That is the compiler's job.

- **(A) is wrong:** Protection.
- **(B) is wrong:** File management.
- **(D) is wrong:** Resource management.

Re-read: [Lesson 0.1.2](#l-0-1-2) — What an operating system does: kernel, user mode and kernel mode, interrupts

**Q6** Answer: (B) (C) (D)2 marks

Reading a register is harmless.

- **(A) is wrong:** Not privileged.

Re-read: [Lesson 0.1.2](#l-0-1-2) — What an operating system does: kernel, user mode and kernel mode, interrupts

**Q7** Answer: (A)1 mark

Device-generated.

- **(B) is wrong:** Traps come from the running program.
- **(C) is wrong:** The program did not request it at that moment.
- **(D) is wrong:** Privileged instructions are run by the kernel; they are not signals from devices.

Re-read: [Lesson 0.1.2](#l-0-1-2) — What an operating system does: kernel, user mode and kernel mode, interrupts

**Q8** Answer: (D)1 mark

Definition.

- **(A) is wrong:** That is multiprocessing.
- **(B) is wrong:** A scheduling parameter.
- **(C) is wrong:** Not the definition.

Re-read: [Lesson 0.1.2](#l-0-1-2) — What an operating system does: kernel, user mode and kernel mode, interrupts

**Q9** Answer: (A)1 mark

Missing the deadline is a failure.

- **(B) is wrong:** Fair, not deadline-driven.
- **(C) is wrong:** A structure, not a guarantee.
- **(D) is wrong:** No deadlines.

Re-read: [Lesson 0.1.2](#l-0-1-2) — What an operating system does: kernel, user mode and kernel mode, interrupts

**Q10** Answer: 121 mark

One per call (plus one switch back each).

Re-read: [Lesson 0.1.3](#l-0-1-3) — System calls: how programs ask the operating system for help

**Q11** Answer: (C)1 mark

Creates a process in the kernel.

- **(A) is wrong:** Library.
- **(B) is wrong:** Library.
- **(D) is wrong:** Library.

Re-read: [Lesson 0.1.3](#l-0-1-3) — System calls: how programs ask the operating system for help

**Q12** Answer: (B)2 marks

The number selects the handler.

- **(A) is wrong:** Unrelated.
- **(C) is wrong:** Unrelated.
- **(D) is wrong:** The kernel never sees source code.

Re-read: [Lesson 0.1.3](#l-0-1-3) — System calls: how programs ask the operating system for help

**Q13** Answer: (A) (B) (C)2 marks

User programs cannot write kernel memory.

- **(D) is wrong:** Blocked by protection.

Re-read: [Lesson 0.1.3](#l-0-1-3) — System calls: how programs ask the operating system for help

**Q14** Answer: (C)1 mark

Most services run inside the kernel.

- **(A) is wrong:** Linux is not a microkernel.
- **(B) is wrong:** General-purpose.
- **(D) is wrong:** It is interactive.

Re-read: [Lesson 0.1.3](#l-0-1-3) — System calls: how programs ask the operating system for help

**Q15** Answer: 10485762 marks

2³²/2¹² = 2²⁰.

Re-read: [Lesson 0.1.1](#l-0-1-1) — Inside a computer: CPU, memory, disk, I/O; bits, bytes and powers of two

Type next → [**1.1.1** Processes: memory layout, process control block and process states](#l-1-1-1)

# ⚙️Phase 1 — Processes & Threads

## 📄Lesson 1.1.1 — Processes: memory layout, process control block and process states

Phase 1 › Processes & Threads › Chapter 1.1 Processes › Topic 1.1.1

Phase 1Ch 1.1 ProcessesTopic 1.1.1GATE weight: High≈ 40 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. One system call causes how many mode switches? from [Lesson 0.1.3](#l-0-1-3)
2. What does the timer interrupt let the OS do? from [Lesson 0.1.2](#l-0-1-2)
3. Program vs process? from [Lesson 0.1.1](#l-0-1-1)

### 1The Hook

🎣

Open a browser, a music player and a terminal: three processes. Only one can use a single CPU at any instant, so at every moment most of them are **waiting** for something: the CPU, a key press, a disk read. The OS tracks each one with a record card and moves it between a handful of **states**. GATE asks which state changes are possible and what the record card holds.

### 2Predict First

🤔

A process asks to read a file from disk. Reading takes a long time compared with the CPU. Should the process keep the CPU while it waits?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

**No.** It moves to a **waiting** (blocked) state and the CPU is given to another process. When the disk finishes, the process becomes **ready** again and waits for its turn on the CPU.

🗣️

In plain words

A **process** is a running program with its own memory area. The OS keeps a **process control block** (PCB), a record card with everything needed to pause and resume it. A process is always in one state: just created, ready to run, running, waiting for something, or finished.

#### 1. A process in memory

| Region | Holds | Grows |
| --- | --- | --- |
| **Text** (code) | the program's instructions | fixed |
| **Data** | global and static variables | fixed |
| **Heap** | memory allocated at run time (malloc, new) | upwards |
| **Stack** | function calls: local variables, parameters, return addresses | downwards |

#### 2. The process control block (PCB)

One per process, kept by the kernel: **process ID (PID)**, **state**, **program counter** (next instruction), **CPU registers**, scheduling information (priority), memory-management information (page table), list of open files, accounting information. Saving and loading PCBs is how the OS pauses and resumes processes.

#### 3. The five states

| State | Meaning |
| --- | --- |
| **New** | being created |
| **Ready** | could run; waiting only for the CPU |
| **Running** | instructions are executing on the CPU |
| **Waiting** (blocked) | waiting for an event: I/O completion, a signal, a resource |
| **Terminated** | finished |

#### 4. The transitions

| From → To | Cause |
| --- | --- |
| New → Ready | admitted by the OS |
| Ready → Running | **dispatched** by the scheduler |
| Running → Ready | **pre-empted** (timer interrupt, a higher-priority process arrives) |
| Running → Waiting | requests I/O or waits for an event |
| Waiting → Ready | the event happens (I/O finishes) |
| Running → Terminated | exit |

**Impossible directly**: Waiting → Running (it must go through Ready), Ready → Waiting (it is not running, so it cannot request anything), New → Running.

#### 5. Suspended states

When memory is short, the OS can **swap** a process out to disk: **Ready → Suspended-ready** and **Waiting → Suspended-waiting** (handled by the medium-term scheduler, Lesson 1.1.2). Suspended-waiting becomes Suspended-ready when its event happens; swapping back in returns it to Ready.

### 4Visual

The five-state model. There is no arrow from Waiting straight to Running, nor from Ready to Waiting.

```
A process's memory (high addresses at the top)

 +-----------+
 |   stack   |  local variables, return addresses   (grows down)
 |     |     |
 |     v     |
 |           |
 |     ^     |
 |     |     |
 |   heap    |  malloc / new                         (grows up)
 +-----------+
 |   data    |  globals, statics
 +-----------+
 |   text    |  machine code
 +-----------+
```

### 5Worked Examples

Example 1 Easy

A running process's time slice ends. Which state does it move to?

Solution

**Ready** (pre-empted).

Example 2 Medium

Where does a local variable of a function live: data, heap or stack?

Solution

**Stack.**

Example 3 GATE

Which transition is NOT possible in the five-state model: Running → Waiting, Waiting → Ready, Waiting → Running, Ready → Running?

Solution

**Waiting → Running**: a woken process must first become Ready.

### 6GATE Traps

⚠️

- Waiting → Running directly is impossible; so is Ready → Waiting.
- Pre-emption sends Running → **Ready**, not Waiting.
- Globals are in **data**, malloc'd memory in the **heap**, locals on the **stack**.
- The PCB is kept by the kernel, not inside the process's own memory.

### 7Memory Hook

🧠

**"Ready waits for the CPU; Waiting waits for an event."**

### 8Connect the Dots

Processes have to come from somewhere. Next lesson creates them with **fork()**, a GATE favourite for counting questions, and meets the schedulers that move processes between states.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**MCQ1 markTransitions

Which state transition is impossible?

1. (A) Ready → Running
2. (B) Waiting → Running
3. (C) Running → Waiting
4. (D) Running → Ready

**Q2**MCQ1 markCause

A process in the Waiting state moves to Ready when:

1. (A) the event it was waiting for occurs
2. (B) the scheduler dispatches it
3. (C) it calls exit
4. (D) its time slice ends

**Q3**MSQ2 marksPCB

Which items are stored in a process control block?

1. (A) Program counter
2. (B) List of open files
3. (C) CPU register values
4. (D) The source code of the program

**Q4**MCQ1 markMemory layout

Memory obtained with malloc comes from the:

1. (A) data segment
2. (B) stack
3. (C) text segment
4. (D) heap

**Q5**MCQ1 markSuspension

Memory is short, so the OS swaps a Waiting process out to disk. Its new state is:

1. (A) Ready
2. (B) Terminated
3. (C) Suspended-waiting
4. (D) Running

### 10Rule Card

- Process memory: text (code), data (globals), heap (dynamic, grows up), stack (calls, grows down).
- PCB: PID, state, program counter, registers, scheduling info, memory info, open files, accounting.
- States: New, Ready, Running, Waiting, Terminated.
- Transitions: admit, dispatch (Ready→Running), pre-empt (Running→Ready), I/O request (Running→Waiting), event done (Waiting→Ready), exit. Waiting→Running and Ready→Waiting are impossible.
- Suspended-ready / suspended-waiting via swapping.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

processtext, data, heap and stack segmentsprocess control blockprocess IDprogram counterprocess statesdispatchpre-emptionblocking on I/Oimpossible transitionssuspended statesswapping

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. 2.
2. Take the CPU back from a running process.
3. A process is a program in execution.

#### Self-Test

**Q1** Answer: (B)1 mark

A woken process goes to Ready first.

- **(A) is wrong:** Dispatch.
- **(C) is wrong:** I/O request.
- **(D) is wrong:** Pre-emption.

Re-read: [Lesson 1.1.1](#l-1-1-1) — Processes: memory layout, process control block and process states

**Q2** Answer: (A)1 mark

I/O completion or a signal.

- **(B) is wrong:** That moves Ready → Running.
- **(C) is wrong:** That ends the process.
- **(D) is wrong:** That moves Running → Ready.

Re-read: [Lesson 1.1.1](#l-1-1-1) — Processes: memory layout, process control block and process states

**Q3** Answer: (A) (B) (C)2 marks

Code is in memory/disk, not the PCB.

- **(D) is wrong:** Not part of the PCB.

Re-read: [Lesson 1.1.1](#l-1-1-1) — Processes: memory layout, process control block and process states

**Q4** Answer: (D)1 mark

Run-time allocation.

- **(A) is wrong:** Globals and statics.
- **(B) is wrong:** Locals and call frames.
- **(C) is wrong:** Code only.

Re-read: [Lesson 1.1.1](#l-1-1-1) — Processes: memory layout, process control block and process states

**Q5** Answer: (C)1 mark

Swapped out while still waiting for its event.

- **(A) is wrong:** Its event has not happened.
- **(B) is wrong:** It has not finished.
- **(D) is wrong:** It is not on the CPU.

Re-read: [Lesson 1.1.1](#l-1-1-1) — Processes: memory layout, process control block and process states

Type next → [**1.1.2** Creating processes with fork(), exec() and wait(); context switches and schedulers](#l-1-1-2)

## 📄Lesson 1.1.2 — Creating processes with fork(), exec() and wait(); context switches and schedulers

Phase 1 › Processes & Threads › Chapter 1.1 Processes › Topic 1.1.2

Phase 1Ch 1.1 ProcessesTopic 1.1.2GATE weight: High≈ 45 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. Pre-emption moves a process from Running to? from [Lesson 1.1.1](#l-1-1-1)
2. Is fork a system call? from [Lesson 0.1.3](#l-0-1-3)
3. 2⁴? from [Lesson 0.1.1](#l-0-1-1)

### 1The Hook

🎣

In UNIX, every process (except the very first) is created by copying an existing one with **fork()**. The copy starts life at the same line as its parent, so a few forks inside a loop multiply processes surprisingly fast. "How many times is hello printed?" is one of the most common GATE OS questions, and it has a simple, reliable method.

### 2Predict First

🤔

This program runs: `fork(); fork(); printf("hi\n");`. How many times is "hi" printed?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

The first fork makes 2 processes; each of them runs the second fork, making 4. All 4 print: **4 times**.

🗣️

In plain words

**fork()** makes an almost exact copy of the calling process. Both copies continue from the line after the fork. The only difference is the value fork returns: **0 in the child**, and the child's ID (a positive number) in the parent. Each fork doubles the number of processes that execute it.

#### 1. fork(), exec(), wait(), exit()

- **fork()**: creates a child that is a copy of the parent (same code, a **copy** of data, heap and stack, same open files). Returns **0 to the child**, the **child's PID (> 0) to the parent**, −1 on failure.
- **exec()**: replaces the current process's program with a new one (same PID; the old code is gone).
- **wait()**: the parent pauses until a child exits.
- **exit()**: the process ends.
- After fork, parent and child have **separate** memory: a change to a variable in one is invisible to the other.

#### 2. Counting processes and prints

- n forks executed one after another (or in a loop of n iterations): **2ⁿ processes** in all, **2ⁿ − 1 children** created.
- A print after the forks runs once per process.
- A print **inside** the loop runs once per process alive at that iteration: `for (i = 0; i < 3; i++) { fork(); printf("x"); }` prints 2 + 4 + 8 = **14**.
- Conditions split the processes. `if (fork() == 0) fork(); printf("y");` → only the child forks again → **3 processes, 3 prints**.
- Short-circuit operators: in `fork() && fork() || fork()`, a process where the first fork returned 0 skips the second fork. Draw the tree: **5 processes**.

#### 3. Zombies and orphans

- **Zombie**: the child has exited but the parent has not yet called wait(), so its PCB entry remains.
- **Orphan**: the parent exited first; the child is adopted by the init process.

#### 4. Context switch

Switching the CPU from one process to another: **save** the old process's state into its PCB and **load** the new one's. It is pure overhead (no useful work), typically microseconds.

#### 5. The three schedulers

| Scheduler | Decides | How often |
| --- | --- | --- |
| **Long-term** (job) | which new jobs are admitted to memory; controls the degree of multiprogramming | rarely |
| **Short-term** (CPU) | which ready process gets the CPU next | very often (milliseconds) |
| **Medium-term** | which processes to swap out and back in | in between |

A good mix of **I/O-bound** processes (short CPU bursts, lots of waiting) and **CPU-bound** processes (long CPU bursts) keeps both the CPU and the devices busy.

### 4Visual

fork(); fork(); — after two forks there are 4 processes (the original and 3 children); a printf after them runs 4 times.

### 5Worked Examples

Example 1 Easy

`for (i = 0; i < 4; i++) fork();` How many processes exist at the end (including the original)?

Solution

2⁴ = **16** (15 children).

Example 2 Medium

`int x = 5; if (fork() == 0) x = x + 5; else x = x − 5; printf("%d", x);` What is printed?

Solution

Two lines: **10** (child) and **0** (parent), in either order. Each has its own copy of x.

Example 3 GATE

`printf("start"); fork(); printf("A"); fork(); printf("B");` How many lines are printed in total?

Solution

"start" once, "A" twice, "B" four times: **7**.

### 6GATE Traps

⚠️

- fork returns **0 in the child**, not in the parent.
- Variables are **copied**, not shared, after fork.
- n forks → 2ⁿ processes but 2ⁿ − 1 **children**; read which one is asked.
- Prints inside a loop are counted per iteration (2 + 4 + 8 …), not once at the end.

### 7Memory Hook

🧠

**"Each fork doubles whoever reaches it; child gets 0."**

### 8Connect the Dots

Chapter 1.1 is complete. Copying a whole process is expensive. **Threads** let one process run several tasks that share its memory. They come next, together with the ways separate processes talk to each other (IPC).

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**NAT1 markLoop

`for (i = 0; i < 5; i++) fork();` How many child processes are created?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT2 marksPrints in a loop

`for (i = 0; i < 3; i++) { fork(); printf("x"); }` How many x's are printed in total?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT2 marksConditions

`if (fork() && fork()) fork();` How many processes exist in total (including the original)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**NAT2 marksShort circuit

`fork() && fork() || fork();` How many processes exist in total (including the original)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**MCQ1 markSchedulers

Which scheduler controls the degree of multiprogramming?

1. (A) Long-term
2. (B) Short-term
3. (C) Dispatcher
4. (D) Medium-term

### 10Rule Card

- fork: child is a copy; returns 0 in child, child PID in parent; memory is copied, not shared.
- n sequential forks → 2ⁿ processes, 2ⁿ − 1 children; prints after forks happen once per process; inside a loop, add per iteration.
- exec replaces the program; wait waits for a child; zombie = exited, not waited for; orphan = parent gone.
- Context switch = save + load PCB (overhead).
- Long-term (admission, degree of multiprogramming), short-term (CPU), medium-term (swapping).

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

forkreturn values of forkexecwaitexitcopied address spacecounting processes and printsfork treesshort-circuit evaluation with forkzombie processorphan processcontext switchlong-term, short-term and medium-term schedulersdispatcherI/O-bound vs CPU-bound

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. Ready.
2. Yes.
3. 16.

#### Self-Test

**Q1** Answer: 311 mark

2⁵ − 1.

Re-read: [Lesson 1.1.2](#l-1-1-2) — Creating processes with fork(), exec() and wait(); context switches and schedulers

**Q2** Answer: 142 marks

2 + 4 + 8.

Re-read: [Lesson 1.1.2](#l-1-1-2) — Creating processes with fork(), exec() and wait(); context switches and schedulers

**Q3** Answer: 42 marks

Only the original passes both conditions and forks a third time.

Re-read: [Lesson 1.1.2](#l-1-1-2) — Creating processes with fork(), exec() and wait(); context switches and schedulers

**Q4** Answer: 52 marks

Draw the tree: 2 from the first fork, the parent's && adds 1, the two zeros each run the third fork.

Re-read: [Lesson 1.1.2](#l-1-1-2) — Creating processes with fork(), exec() and wait(); context switches and schedulers

**Q5** Answer: (A)1 mark

It admits new jobs into memory.

- **(B) is wrong:** Picks from those already ready.
- **(C) is wrong:** Performs the switch the short-term scheduler chose.
- **(D) is wrong:** Swaps, but admission is long-term.

Re-read: [Lesson 1.1.2](#l-1-1-2) — Creating processes with fork(), exec() and wait(); context switches and schedulers

Type next → [**LI-1.1** Chapter 1.1 Lock-in](#l-LI-1-1)

## 🔒Chapter 1.1 Lock-in — Processes

Phase 1 › Processes & Threads › Chapter 1.1 Processes

Phase 1Ch 1.1 Processes

### ACompressed recap

🧾

Process = text, data, heap, stack + PCB (PID, state, PC, registers, open files). States New, Ready, Running, Waiting, Terminated; no Waiting → Running or Ready → Waiting. fork: 0 to child, PID to parent, copied memory; 2ⁿ processes from n forks; loops add per iteration. Zombie, orphan; context switch overhead; long/short/medium-term schedulers.

### BMerged rule card

[1.1.1](#l-1-1-1) Processes: memory layout, process control block and process states

- Process memory: text (code), data (globals), heap (dynamic, grows up), stack (calls, grows down).
- PCB: PID, state, program counter, registers, scheduling info, memory info, open files, accounting.
- States: New, Ready, Running, Waiting, Terminated.
- Transitions: admit, dispatch (Ready→Running), pre-empt (Running→Ready), I/O request (Running→Waiting), event done (Waiting→Ready), exit. Waiting→Running and Ready→Waiting are impossible.
- Suspended-ready / suspended-waiting via swapping.

[1.1.2](#l-1-1-2) Creating processes with fork(), exec() and wait(); context switches and schedulers

- fork: child is a copy; returns 0 in child, child PID in parent; memory is copied, not shared.
- n sequential forks → 2ⁿ processes, 2ⁿ − 1 children; prints after forks happen once per process; inside a loop, add per iteration.
- exec replaces the program; wait waits for a child; zombie = exited, not waited for; orphan = parent gone.
- Context switch = save + load PCB (overhead).
- Long-term (admission, degree of multiprogramming), short-term (CPU), medium-term (swapping).

### CInterleaved GATE-style questions

**Q1**MCQ1 markStates

A process requests a disk read. It moves from Running to:

1. (A) Terminated
2. (B) Waiting
3. (C) New
4. (D) Ready

**Q2**MCQ1 markLayout

A global variable `int count = 0;` is stored in the:

1. (A) heap
2. (B) PCB
3. (C) stack
4. (D) data segment

**Q3**NAT1 markFork

`fork(); fork(); fork(); printf("hi");` How many times is hi printed?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**NAT2 marksFork

`if (fork() == 0) fork(); printf("y");` How many times is y printed?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**NAT2 marksFork

`for (i = 0; i < 2; i++) { if (fork() == 0) printf("c"); }` How many c's are printed?

Numerical answer: \_\_\_\_\_\_\_\_

**Q6**MCQ1 markReturn value

In the parent process, fork() returns:

1. (A) the parent's own PID
2. (B) 0
3. (C) the child's PID
4. (D) −1 always

**Q7**MCQ1 markZombie

A child has exited but its parent has not called wait(). The child is a(n):

1. (A) zombie
2. (B) thread
3. (C) daemon
4. (D) orphan

**Q8**MSQ2 marksAfter fork

Immediately after a successful fork(), which are true?

1. (A) The child's fork() returned 0.
2. (B) A change to a global variable in the child is seen by the parent.
3. (C) Parent and child run the same code.
4. (D) Both continue from the statement after fork().

### DAnswer Vault

🔐 Open the Answer Vault

**Q1** Answer: (B)1 mark

It must wait for the I/O.

- **(A) is wrong:** It has not finished.
- **(C) is wrong:** Not a backward transition.
- **(D) is wrong:** Ready means only the CPU is missing.

Re-read: [Lesson 1.1.1](#l-1-1-1) — Processes: memory layout, process control block and process states

**Q2** Answer: (D)1 mark

Globals and statics.

- **(A) is wrong:** Dynamic memory.
- **(B) is wrong:** Kernel bookkeeping.
- **(C) is wrong:** Locals.

Re-read: [Lesson 1.1.1](#l-1-1-1) — Processes: memory layout, process control block and process states

**Q3** Answer: 81 mark

2³.

Re-read: [Lesson 1.1.2](#l-1-1-2) — Creating processes with fork(), exec() and wait(); context switches and schedulers

**Q4** Answer: 32 marks

Parent prints once; the child forks, so two more.

Re-read: [Lesson 1.1.2](#l-1-1-2) — Creating processes with fork(), exec() and wait(); context switches and schedulers

**Q5** Answer: 32 marks

One new child in iteration 0, two new children in iteration 1; each child prints once.

Re-read: [Lesson 1.1.2](#l-1-1-2) — Creating processes with fork(), exec() and wait(); context switches and schedulers

**Q6** Answer: (C)1 mark

The child gets 0.

- **(A) is wrong:** The parent already knows its PID.
- **(B) is wrong:** That is the child's value.
- **(D) is wrong:** Only on failure.

Re-read: [Lesson 1.1.2](#l-1-1-2) — Creating processes with fork(), exec() and wait(); context switches and schedulers

**Q7** Answer: (A)1 mark

Its entry stays until reaped.

- **(B) is wrong:** Not related.
- **(C) is wrong:** A background service.
- **(D) is wrong:** Orphans have lost their parent.

Re-read: [Lesson 1.1.2](#l-1-1-2) — Creating processes with fork(), exec() and wait(); context switches and schedulers

**Q8** Answer: (A) (C) (D)2 marks

Memory is copied.

- **(B) is wrong:** Separate copies.

Re-read: [Lesson 1.1.2](#l-1-1-2) — Creating processes with fork(), exec() and wait(); context switches and schedulers

Type next → [**1.2.1** Threads: what they share, user-level vs kernel-level threads](#l-1-2-1)

## 📄Lesson 1.2.1 — Threads: what they share, user-level vs kernel-level threads

Phase 1 › Processes & Threads › Chapter 1.2 Threads and IPC › Topic 1.2.1

Phase 1Ch 1.2 Threads and IPCTopic 1.2.1GATE weight: Medium≈ 35 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. After fork, are variables shared? from [Lesson 1.1.2](#l-1-1-2)
2. Which segment holds local variables? from [Lesson 1.1.1](#l-1-1-1)
3. Interrupts come from? from [Lesson 0.1.2](#l-0-1-2)

### 1The Hook

🎣

A web browser downloads an image, plays a video and responds to your scroll, all at once, inside one process. It uses **threads**: several lines of execution sharing the same memory. Threads are cheaper than processes and share data easily, which is also why they need careful synchronization (Phase 3). GATE asks what threads share and how user-level and kernel-level threads differ.

### 2Predict First

🤔

Two threads of one process both use a global variable `count`. One sets it to 5. Does the other see 5?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

**Yes.** Threads of the same process share global data (unlike processes after fork, which get copies).

🗣️

In plain words

A **thread** is one path of execution inside a process. All threads of a process share its code, its global data, its heap and its open files, but each thread has its own **stack**, **registers** and **program counter** (so each can be at a different line, inside different function calls).

#### 1. Shared vs private

| Shared by all threads of a process | Private to each thread |
| --- | --- |
| code (text) | thread ID |
| global/static data | program counter |
| heap | registers |
| open files, signals | **stack** (local variables) |

#### 2. Why threads?

- **Cheaper** than processes: creating a thread and switching between threads of the same process costs much less (no new address space).
- **Sharing** data is easy (same memory).
- **Responsiveness** and use of multiple CPU cores.

#### 3. User-level vs kernel-level threads

|  | User-level threads | Kernel-level threads |
| --- | --- | --- |
| Managed by | a library in user space | the OS kernel |
| Kernel knows about them? | no (sees one process) | yes |
| Switching | very fast (no system call) | slower (kernel involved) |
| One thread blocks on I/O | **the whole process blocks** | only that thread blocks |
| Use several CPUs at once | no | yes |

#### 4. Multithreading models (user threads → kernel threads)

- **Many-to-one**: many user threads on one kernel thread (one blocking call blocks all).
- **One-to-one**: each user thread has its own kernel thread (Linux, Windows); true parallelism, more overhead.
- **Many-to-many**: many user threads multiplexed onto a smaller or equal number of kernel threads.

### 4Visual

```
One process, three threads

 +--------------------------------------------+
 |  code      |  global data  |  heap  | files |   <- shared by all threads
 +--------------------------------------------+
 |  thread 1        thread 2        thread 3   |
 |  [stack 1]       [stack 2]       [stack 3]  |   <- private
 |  PC, regs        PC, regs        PC, regs   |
 +--------------------------------------------+
```

### 5Worked Examples

Example 1 Easy

Do two threads of a process share their local variables?

Solution

**No**: locals live on each thread's own stack.

Example 2 Medium

A process uses only user-level threads. One thread makes a blocking read. What happens to the other threads?

Solution

They **all block**: the kernel sees one process, which is now waiting.

Example 3 GATE

Which is cheaper: switching between two threads of the same process, or between two processes?

Solution

**Between threads of the same process**: no change of address space is needed.

### 6GATE Traps

⚠️

- Threads share the heap and globals but **not** the stack or registers.
- User-level threads block together on a blocking system call.
- Kernel threads can run in parallel on multiple CPUs; many-to-one user threads cannot.
- fork copies memory; threads share it.

### 7Memory Hook

🧠

**"Threads share the house, each has its own notebook (stack)."**

### 8Connect the Dots

Threads share memory automatically. Separate processes don't, so they need **inter-process communication**: shared memory regions, messages or pipes, the topic of the next lesson.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**MSQ2 marksSharing

Which are shared by all threads of a process?

1. (A) Global variables
2. (B) Stack
3. (C) Open files
4. (D) Heap

**Q2**MCQ1 markPrivate

Which does each thread have its own copy of?

1. (A) Code
2. (B) Heap
3. (C) Open-file table
4. (D) Program counter

**Q3**MCQ1 markUser-level threads

With purely user-level threads, a blocking system call by one thread:

1. (A) crashes the process
2. (B) blocks the whole process
3. (C) blocks only that thread
4. (D) is impossible

**Q4**MCQ1 markModels

Linux maps each user thread to its own kernel thread. This is the:

1. (A) many-to-many model
2. (B) one-to-one model
3. (C) many-to-one model
4. (D) no-thread model

**Q5**MCQ1 markCost

Which is the main reason threads are cheaper to create than processes?

1. (A) They share the existing address space.
2. (B) They run in kernel mode.
3. (C) They never make system calls.
4. (D) They have no stack.

### 10Rule Card

- Thread = path of execution inside a process; shares code, data, heap, open files; private stack, registers, PC, thread ID.
- Threads are cheaper to create and switch than processes.
- User-level: fast, kernel unaware, one block blocks all, no parallelism. Kernel-level: kernel-scheduled, independent blocking, parallel on multiple cores.
- Models: many-to-one, one-to-one, many-to-many.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

threadshared and private thread resourcesbenefits of threadsuser-level threadskernel-level threadsblocking behaviourmany-to-one, one-to-one and many-to-many models

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. No, they are copied.
2. The stack.
3. Hardware devices.

#### Self-Test

**Q1** Answer: (A) (C) (D)2 marks

Each thread has its own stack.

- **(B) is wrong:** Private.

Re-read: [Lesson 1.2.1](#l-1-2-1) — Threads: what they share, user-level vs kernel-level threads

**Q2** Answer: (D)1 mark

Each thread can be at a different instruction.

- **(A) is wrong:** Shared.
- **(B) is wrong:** Shared.
- **(C) is wrong:** Shared.

Re-read: [Lesson 1.2.1](#l-1-2-1) — Threads: what they share, user-level vs kernel-level threads

**Q3** Answer: (B)1 mark

The kernel sees only one schedulable entity.

- **(A) is wrong:** Nothing crashes.
- **(C) is wrong:** That is kernel-level behaviour.
- **(D) is wrong:** It is possible.

Re-read: [Lesson 1.2.1](#l-1-2-1) — Threads: what they share, user-level vs kernel-level threads

**Q4** Answer: (B)1 mark

One kernel thread per user thread.

- **(A) is wrong:** Multiplexed.
- **(C) is wrong:** Many user threads on one kernel thread.
- **(D) is wrong:** Not a model.

Re-read: [Lesson 1.2.1](#l-1-2-1) — Threads: what they share, user-level vs kernel-level threads

**Q5** Answer: (A)1 mark

No new memory map to build.

- **(B) is wrong:** Not in general.
- **(C) is wrong:** They may.
- **(D) is wrong:** Each thread has a stack.

Re-read: [Lesson 1.2.1](#l-1-2-1) — Threads: what they share, user-level vs kernel-level threads

Type next → [**1.2.2** Inter-process communication: shared memory, message passing and pipes](#l-1-2-2)

## 📄Lesson 1.2.2 — Inter-process communication: shared memory, message passing and pipes

Phase 1 › Processes & Threads › Chapter 1.2 Threads and IPC › Topic 1.2.2

Phase 1Ch 1.2 Threads and IPCTopic 1.2.2GATE weight: Medium≈ 35 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. What does each thread keep privately? from [Lesson 1.2.1](#l-1-2-1)
2. fork returns what in the child? from [Lesson 1.1.2](#l-1-1-2)
3. Name the five process states. from [Lesson 1.1.1](#l-1-1-1)

### 1The Hook

🎣

In a terminal, `ls | sort` sends the output of one program into another. Two separate processes cooperate even though neither can see the other's memory. **Inter-process communication** (IPC) is how: through a shared region of memory, by passing messages, or through a pipe. GATE asks the trade-offs.

### 2Predict First

🤔

Two processes want to exchange 1 GB of data many times. Is it faster to copy it through the kernel each time, or to let both map the same memory region?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

**Shared memory**: once set up, the data is not copied through the kernel at all. Message passing copies every message.

🗣️

In plain words

Processes have separate memories. To cooperate they either **share** a piece of memory (like a shared whiteboard: fast, but they must take turns) or **send messages** through the OS (like posting letters: slower, but the OS keeps order). A **pipe** is a one-way message channel, like a tube from one process to another.

#### 1. Shared memory

- The OS maps one region into both processes' address spaces (system calls such as shmget/shmat or mmap).
- After setup, reading and writing are ordinary memory accesses: **fast**, no kernel involvement.
- The processes must **synchronize** themselves (Phase 3), or they will overwrite each other's data.

#### 2. Message passing

- Two operations: **send(message)** and **receive(message)**, implemented by the kernel.
- **Direct** (name the process) or **indirect** (through a mailbox or port).
- **Blocking** (synchronous) send waits until the message is received; **non-blocking** send returns at once. Same for receive.
- Simpler to use and works across machines (sockets), but each message is copied through the kernel (slower for big data).

#### 3. Pipes

- An **ordinary pipe** (`pipe()` system call) is **unidirectional**: one end for writing, one for reading; usually between a parent and a child created with fork. For two-way traffic you need two pipes.
- A **named pipe** (FIFO) has a name in the file system and can connect unrelated processes.
- A read from an empty pipe blocks; a write to a full pipe blocks.

#### 4. The producer–consumer pattern

One process produces items, another consumes them, through a buffer of fixed size. The producer must wait when the buffer is **full**, the consumer when it is **empty**. Getting this right needs the synchronization tools of Phase 3 (Lesson 3.2.2).

### 4Visual

|  | Shared memory | Message passing |
| --- | --- | --- |
| Speed for large data | fast (no copying after setup) | slower (kernel copies each message) |
| Kernel involvement | only at setup | every send and receive |
| Synchronization | programmer's job | built into send/receive |
| Across machines | no | yes (sockets) |

```
ls | sort   with an ordinary pipe

  [ ls ] --write--> [=====pipe=====] --read--> [ sort ]
                one direction only
```

### 5Worked Examples

Example 1 Easy

How many ordinary pipes are needed for two-way communication between parent and child?

Solution

**2** (pipes are one-way).

Example 2 Medium

Which IPC method needs explicit synchronization by the programmer?

Solution

**Shared memory.**

Example 3 GATE

A process does a blocking receive on an empty mailbox. What happens?

Solution

It **waits** (blocks) until a message arrives.

### 6GATE Traps

⚠️

- Ordinary pipes are **one-way**.
- Shared memory is fast but **not** automatically synchronized.
- Message passing copies data through the kernel each time.
- Blocking send waits for the receiver; non-blocking returns immediately.

### 7Memory Hook

🧠

**"Shared memory: fast whiteboard, take turns. Messages: letters through the OS."**

### 8Connect the Dots

Phase 1 is complete: processes, fork, threads and IPC. Phase 2 answers the question the short-term scheduler faces thousands of times a second: **which ready process runs next?**

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**MCQ1 markSpeed

For exchanging large amounts of data between two processes on one machine, the fastest method after setup is usually:

1. (A) message passing
2. (B) sockets
3. (C) shared memory
4. (D) ordinary pipes

**Q2**MCQ1 markPipes

An ordinary (anonymous) pipe is:

1. (A) stored permanently on disk
2. (B) usable between any two unrelated processes
3. (C) bidirectional
4. (D) unidirectional

**Q3**MSQ2 marksMessage passing

Which are true of message passing?

1. (A) It never blocks.
2. (B) It is often simpler to program correctly than shared memory.
3. (C) The kernel is involved in each send and receive.
4. (D) It can work between processes on different machines.

**Q4**NAT1 markPipes

A parent wants two-way communication with each of its 3 children using ordinary pipes. Minimum number of pipes?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**MCQ1 markProducer–consumer

In the bounded-buffer producer–consumer problem, the producer must wait when:

1. (A) the buffer is empty
2. (B) the buffer is full
3. (C) the consumer is running
4. (D) never

### 10Rule Card

- Shared memory: map a common region; fast; programmer synchronizes.
- Message passing: send/receive via the kernel; direct or indirect (mailbox); blocking or non-blocking; works across machines; copies data.
- Ordinary pipe: one-way, parent–child; named pipe (FIFO) for unrelated processes; two-way needs two pipes.
- Producer waits when the buffer is full; consumer waits when empty.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

inter-process communicationshared memorymessage passingsend and receivedirect and indirect communicationmailboxesblocking and non-blocking operationsordinary pipesnamed pipes (FIFOs)producer–consumer with a bounded buffer

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. Stack, registers, program counter.
2. 0.
3. New, ready, running, waiting, terminated.

#### Self-Test

**Q1** Answer: (C)1 mark

No copying through the kernel.

- **(A) is wrong:** Copies every message.
- **(B) is wrong:** Copies through the kernel.
- **(D) is wrong:** Copies through the kernel.

Re-read: [Lesson 1.2.2](#l-1-2-2) — Inter-process communication: shared memory, message passing and pipes

**Q2** Answer: (D)1 mark

Write end and read end.

- **(A) is wrong:** It lives in memory.
- **(B) is wrong:** Usually parent–child; named pipes connect unrelated ones.
- **(C) is wrong:** Two pipes are needed for two-way traffic.

Re-read: [Lesson 1.2.2](#l-1-2-2) — Inter-process communication: shared memory, message passing and pipes

**Q3** Answer: (B) (C) (D)2 marks

Blocking variants exist.

- **(A) is wrong:** Blocking send/receive wait.

Re-read: [Lesson 1.2.2](#l-1-2-2) — Inter-process communication: shared memory, message passing and pipes

**Q4** Answer: 61 mark

Two per child.

Re-read: [Lesson 1.2.2](#l-1-2-2) — Inter-process communication: shared memory, message passing and pipes

**Q5** Answer: (B)1 mark

No space to put an item.

- **(A) is wrong:** That is when the consumer waits.
- **(C) is wrong:** Not by itself a reason.
- **(D) is wrong:** It must wait when full.

Re-read: [Lesson 1.2.2](#l-1-2-2) — Inter-process communication: shared memory, message passing and pipes

Type next → [**LI-1.2** Chapter 1.2 Lock-in](#l-LI-1-2)

## 🔒Chapter 1.2 Lock-in — Threads and IPC

Phase 1 › Processes & Threads › Chapter 1.2 Threads and IPC

Phase 1Ch 1.2 Threads and IPC

### ACompressed recap

🧾

Threads share code, globals, heap, files; private stack, registers, PC. User-level threads: fast, all block together; kernel-level: independent, parallel. Models many-to-one, one-to-one, many-to-many. IPC: shared memory (fast, needs sync), message passing (kernel copies, blocking or not), pipes (one-way; named for unrelated processes); producer–consumer waits on full/empty.

### BMerged rule card

[1.2.1](#l-1-2-1) Threads: what they share, user-level vs kernel-level threads

- Thread = path of execution inside a process; shares code, data, heap, open files; private stack, registers, PC, thread ID.
- Threads are cheaper to create and switch than processes.
- User-level: fast, kernel unaware, one block blocks all, no parallelism. Kernel-level: kernel-scheduled, independent blocking, parallel on multiple cores.
- Models: many-to-one, one-to-one, many-to-many.

[1.2.2](#l-1-2-2) Inter-process communication: shared memory, message passing and pipes

- Shared memory: map a common region; fast; programmer synchronizes.
- Message passing: send/receive via the kernel; direct or indirect (mailbox); blocking or non-blocking; works across machines; copies data.
- Ordinary pipe: one-way, parent–child; named pipe (FIFO) for unrelated processes; two-way needs two pipes.
- Producer waits when the buffer is full; consumer waits when empty.

### CInterleaved GATE-style questions

**Q1**MCQ1 markThreads

A process has 4 threads. How many stacks does it have?

1. (A) 1
2. (B) 2
3. (C) 8
4. (D) 4

**Q2**MSQ2 marksKernel threads

Which are advantages of kernel-level threads over user-level threads?

1. (A) The kernel can schedule each thread separately.
2. (B) Thread switches never involve the kernel.
3. (C) A blocking call blocks only that thread.
4. (D) Threads can run in parallel on multiple CPUs.

**Q3**MCQ1 markSharing

Which of these is NOT shared between threads of the same process?

1. (A) Register values
2. (B) Heap memory
3. (C) Code
4. (D) Global variables

**Q4**MCQ1 markModel

In the many-to-one model, the main drawback is:

1. (A) threads cannot share memory
2. (B) too many kernel threads
3. (C) a blocking system call blocks all threads
4. (D) threads cannot be created

**Q5**MCQ1 markIPC

Which IPC mechanism requires the processes themselves to handle synchronization?

1. (A) Blocking pipes
2. (B) Mailboxes
3. (C) Message passing
4. (D) Shared memory

**Q6**NAT1 markPipes

Minimum number of ordinary pipes for full two-way communication between 2 processes?

Numerical answer: \_\_\_\_\_\_\_\_

**Q7**MCQ1 markNamed pipes

Two unrelated processes (not parent and child) want to use a pipe. They should use a:

1. (A) shared stack
2. (B) ordinary pipe
3. (C) named pipe (FIFO)
4. (D) thread

**Q8**MCQ1 markBlocking

A consumer reads from an empty ordinary pipe. It:

1. (A) blocks until data is written
2. (B) terminates the producer
3. (C) reads 0 bytes and crashes
4. (D) reads old data

### DAnswer Vault

🔐 Open the Answer Vault

**Q1** Answer: (D)1 mark

One per thread.

- **(A) is wrong:** Stacks are private.
- **(B) is wrong:** No.
- **(C) is wrong:** No.

Re-read: [Lesson 1.2.1](#l-1-2-1) — Threads: what they share, user-level vs kernel-level threads

**Q2** Answer: (A) (C) (D)2 marks

Kernel threads do need the kernel to switch.

- **(B) is wrong:** That is the user-level advantage.

Re-read: [Lesson 1.2.1](#l-1-2-1) — Threads: what they share, user-level vs kernel-level threads

**Q3** Answer: (A)1 mark

Each thread has its own registers.

- **(B) is wrong:** Shared.
- **(C) is wrong:** Shared.
- **(D) is wrong:** Shared.

Re-read: [Lesson 1.2.1](#l-1-2-1) — Threads: what they share, user-level vs kernel-level threads

**Q4** Answer: (C)1 mark

Only one kernel thread underneath.

- **(A) is wrong:** They share memory.
- **(B) is wrong:** There is only one.
- **(D) is wrong:** They can be created.

Re-read: [Lesson 1.2.1](#l-1-2-1) — Threads: what they share, user-level vs kernel-level threads

**Q5** Answer: (D)1 mark

Plain memory reads and writes.

- **(A) is wrong:** Blocking provides order.
- **(B) is wrong:** Kernel-managed.
- **(C) is wrong:** Built-in ordering.

Re-read: [Lesson 1.2.2](#l-1-2-2) — Inter-process communication: shared memory, message passing and pipes

**Q6** Answer: 21 mark

One per direction.

Re-read: [Lesson 1.2.2](#l-1-2-2) — Inter-process communication: shared memory, message passing and pipes

**Q7** Answer: (C)1 mark

It has a name in the file system.

- **(A) is wrong:** Not a mechanism.
- **(B) is wrong:** Needs a common ancestor.
- **(D) is wrong:** Unrelated.

Re-read: [Lesson 1.2.2](#l-1-2-2) — Inter-process communication: shared memory, message passing and pipes

**Q8** Answer: (A)1 mark

Read on an empty pipe waits.

- **(B) is wrong:** No.
- **(C) is wrong:** It waits.
- **(D) is wrong:** No old data exists.

Re-read: [Lesson 1.2.2](#l-1-2-2) — Inter-process communication: shared memory, message passing and pipes

Type next → [**CP-1** Phase 1 Checkpoint (15 questions)](#l-CP-1)

## ⏱️Phase 1 Checkpoint — Processes & Threads

Phase 1 › Processes & Threads

Phase 1

Phase 1 Checkpoint: 15 questions on processes, fork, threads and IPC.

⏱️

**15 questions · 20 marks · 45 minutes.** Negative marking on MCQ only: −1/3 mark for a wrong 1-mark MCQ, −2/3 for a wrong 2-mark MCQ. No negative marking for MSQ or NAT; MSQ has no partial credit.

**Q1**MCQ1 markStates

Which transition happens when a higher-priority process arrives under pre-emptive scheduling?

1. (A) Ready → Terminated
2. (B) Running → Ready
3. (C) Running → Waiting
4. (D) Waiting → Ready

**Q2**MSQ2 marksTransitions

Which transitions are possible in the five-state model?

1. (A) Waiting → Ready
2. (B) Ready → Waiting
3. (C) Running → Terminated
4. (D) New → Ready

**Q3**MCQ1 markPCB

When a process is pre-empted, its register values are saved in:

1. (A) the program's text segment
2. (B) the disk's boot sector
3. (C) the heap
4. (D) its PCB

**Q4**NAT1 markFork

`for (i = 0; i < 4; i++) fork();` Total number of processes (including the original)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**NAT2 marksFork

`printf("start"); fork(); printf("A"); fork(); printf("B");` Total number of prints?

Numerical answer: \_\_\_\_\_\_\_\_

**Q6**NAT2 marksFork

`if (fork() == 0) { fork(); printf("1"); } else printf("2");` How many times is 1 printed?

Numerical answer: \_\_\_\_\_\_\_\_

**Q7**MCQ2 marksFork values

`int x = 5; if (fork() == 0) x = x + 5; else x = x − 5; printf("%d", x);` What is printed?

1. (A) 10 only
2. (B) 10 and 0, in some order
3. (C) 5 only
4. (D) 5 and 5

**Q8**MCQ1 markSchedulers

Which scheduler runs most often?

1. (A) Long-term
2. (B) Medium-term
3. (C) Short-term
4. (D) All equally

**Q9**MCQ1 markOrphan

A parent exits while its child is still running. The child becomes:

1. (A) an orphan, adopted by init
2. (B) terminated automatically
3. (C) a zombie
4. (D) a thread

**Q10**MSQ2 marksThreads

Which are private to each thread?

1. (A) Heap
2. (B) Stack
3. (C) Program counter
4. (D) Registers

**Q11**MCQ1 markUser threads

Switching between user-level threads of the same process is fast because:

1. (A) it switches the CPU to kernel mode
2. (B) it reloads the whole process's memory
3. (C) it does not require a system call
4. (D) it is done by the disk

**Q12**MCQ1 markThreads vs processes

Compared with processes, threads of one process:

1. (A) share an address space
2. (B) cannot run concurrently
3. (C) have separate address spaces
4. (D) need pipes to share data

**Q13**MCQ1 markIPC

Which IPC method works between processes on different computers?

1. (A) Shared memory
2. (B) Shared heap
3. (C) Ordinary pipes
4. (D) Message passing (sockets)

**Q14**NAT1 markPipes

A parent communicates two-way with each of its 4 children using ordinary pipes. Minimum number of pipes?

Numerical answer: \_\_\_\_\_\_\_\_

**Q15**MCQ1 markProducer–consumer

The consumer must wait when the shared buffer is:

1. (A) never
2. (B) empty
3. (C) full
4. (D) half full

### ✓Answer Vault

🔐 Open the Answer Vault

**Q1** Answer: (B)1 mark

The running process is pre-empted.

- **(A) is wrong:** Impossible.
- **(C) is wrong:** Waiting is for events.
- **(D) is wrong:** Unrelated.

Re-read: [Lesson 1.1.1](#l-1-1-1) — Processes: memory layout, process control block and process states

**Q2** Answer: (A) (C) (D)2 marks

A ready process cannot request I/O.

- **(B) is wrong:** Impossible.

Re-read: [Lesson 1.1.1](#l-1-1-1) — Processes: memory layout, process control block and process states

**Q3** Answer: (D)1 mark

To be restored later.

- **(A) is wrong:** Code is read-only.
- **(B) is wrong:** Unrelated.
- **(C) is wrong:** Not the heap.

Re-read: [Lesson 1.1.1](#l-1-1-1) — Processes: memory layout, process control block and process states

**Q4** Answer: 161 mark

2⁴.

Re-read: [Lesson 1.1.2](#l-1-1-2) — Creating processes with fork(), exec() and wait(); context switches and schedulers

**Q5** Answer: 72 marks

1 + 2 + 4.

Re-read: [Lesson 1.1.2](#l-1-1-2) — Creating processes with fork(), exec() and wait(); context switches and schedulers

**Q6** Answer: 22 marks

The child and the child's child print 1.

Re-read: [Lesson 1.1.2](#l-1-1-2) — Creating processes with fork(), exec() and wait(); context switches and schedulers

**Q7** Answer: (B)2 marks

Separate copies of x.

- **(A) is wrong:** The parent prints too.
- **(C) is wrong:** Both change x.
- **(D) is wrong:** Both change their copy.

Re-read: [Lesson 1.1.2](#l-1-1-2) — Creating processes with fork(), exec() and wait(); context switches and schedulers

**Q8** Answer: (C)1 mark

It picks the next process every few milliseconds.

- **(A) is wrong:** Rare.
- **(B) is wrong:** Occasional.
- **(D) is wrong:** No.

Re-read: [Lesson 1.1.2](#l-1-1-2) — Creating processes with fork(), exec() and wait(); context switches and schedulers

**Q9** Answer: (A)1 mark

It has lost its parent.

- **(B) is wrong:** It continues.
- **(C) is wrong:** Zombie = exited child not reaped.
- **(D) is wrong:** Unrelated.

Re-read: [Lesson 1.1.2](#l-1-1-2) — Creating processes with fork(), exec() and wait(); context switches and schedulers

**Q10** Answer: (B) (C) (D)2 marks

The heap is shared.

- **(A) is wrong:** Shared.

Re-read: [Lesson 1.2.1](#l-1-2-1) — Threads: what they share, user-level vs kernel-level threads

**Q11** Answer: (C)1 mark

The library switches in user mode.

- **(A) is wrong:** No mode switch happens.
- **(B) is wrong:** Threads share the same memory; nothing is reloaded.
- **(D) is wrong:** Unrelated.

Re-read: [Lesson 1.2.1](#l-1-2-1) — Threads: what they share, user-level vs kernel-level threads

**Q12** Answer: (A)1 mark

Same memory.

- **(B) is wrong:** They can.
- **(C) is wrong:** That is processes.
- **(D) is wrong:** They share memory directly.

Re-read: [Lesson 1.2.1](#l-1-2-1) — Threads: what they share, user-level vs kernel-level threads

**Q13** Answer: (D)1 mark

Messages travel over the network.

- **(A) is wrong:** Same machine only.
- **(B) is wrong:** Not a mechanism.
- **(C) is wrong:** Same machine only.

Re-read: [Lesson 1.2.2](#l-1-2-2) — Inter-process communication: shared memory, message passing and pipes

**Q14** Answer: 81 mark

Two per child.

Re-read: [Lesson 1.2.2](#l-1-2-2) — Inter-process communication: shared memory, message passing and pipes

**Q15** Answer: (B)1 mark

Nothing to consume.

- **(A) is wrong:** It must wait when empty.
- **(C) is wrong:** The producer waits then.
- **(D) is wrong:** Fine to consume.

Re-read: [Lesson 1.2.2](#l-1-2-2) — Inter-process communication: shared memory, message passing and pipes

Type next → [**2.1.1** Scheduling basics: the times we measure; first-come first-served](#l-2-1-1)

# ⏱️Phase 2 — CPU Scheduling

## 📄Lesson 2.1.1 — Scheduling basics: the times we measure; first-come first-served

Phase 2 › CPU Scheduling › Chapter 2.1 Basic scheduling algorithms › Topic 2.1.1

Phase 2Ch 2.1 Basic scheduling algorithmsTopic 2.1.1GATE weight: High≈ 45 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. Which scheduler picks the next process for the CPU? from [Lesson 1.1.2](#l-1-1-2)
2. Pre-emption moves a process from Running to? from [Lesson 1.1.1](#l-1-1-1)
3. How many mode switches does one system call cause? from [Lesson 0.1.3](#l-0-1-3)

### 1The Hook

🎣

Three customers queue at a single ticket counter: one needs 24 minutes, two need 3 minutes each. If the slow one goes first, everyone waits ages; if the quick ones go first, the average wait drops from 17 minutes to 3. **CPU scheduling** is choosing that order. GATE asks a scheduling question almost every year, and they all use the same few measurements and one drawing: the **Gantt chart**.

### 2Predict First

🤔

Jobs P1 (24 ms), P2 (3 ms), P3 (3 ms) all arrive at time 0 and run in the order P1, P2, P3. How long does each wait before it starts? What is the average wait?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

P1 waits 0, P2 waits 24, P3 waits 27. Average (0 + 24 + 27)/3 = **17 ms**.

🗣️

In plain words

Each process arrives at some time and needs the CPU for some amount of time (its **burst**). The scheduler decides the order. We draw the order as a timeline (a **Gantt chart**), then read off when each process finished, and from that how long it waited.

#### 1. The times we measure (for each process)

| Name | Meaning | Formula |
| --- | --- | --- |
| Arrival time (AT) | when it enters the ready queue | given |
| Burst time (BT) | CPU time it needs | given |
| Completion time (CT) | when it finishes | read from the Gantt chart |
| **Turnaround time (TAT)** | total time in the system | **CT − AT** |
| **Waiting time (WT)** | time spent in the ready queue | **TAT − BT** |
| **Response time (RT)** | time until it first gets the CPU | first start − AT |

Also: **throughput** = processes finished per unit time; **CPU utilisation** = % of time the CPU is busy.

#### 2. Pre-emptive vs non-pre-emptive

- **Non-pre-emptive**: once a process has the CPU it keeps it until it finishes (or blocks).
- **Pre-emptive**: the OS may take the CPU away (when a better process arrives, or a time slice ends).

#### 3. First-Come First-Served (FCFS)

Run processes in order of arrival; non-pre-emptive. Simple, fair in order, but suffers the **convoy effect**: short jobs stuck behind a long one wait a long time. If the CPU is free and nobody has arrived, it is **idle** until the next arrival.

#### 4. The running example (used all through Phase 2)

| Process | AT | BT | Priority |
| --- | --- | --- | --- |
| P1 | 0 | 8 | 3 |
| P2 | 1 | 4 | 1 |
| P3 | 2 | 9 | 4 |
| P4 | 3 | 5 | 2 |
| P5 | 4 | 2 | 5 |

(Priority is used in Lesson 2.1.3; a smaller number means higher priority.)

FCFS: P1 0–8, P2 8–12, P3 12–21, P4 21–26, P5 26–28.

|  | P1 | P2 | P3 | P4 | P5 |
| --- | --- | --- | --- | --- | --- |
| CT | 8 | 12 | 21 | 26 | 28 |
| TAT = CT − AT | 8 | 11 | 19 | 23 | 24 |
| WT = TAT − BT | 0 | 7 | 10 | 18 | 22 |

Average TAT = 85/5 = **17**; average WT = 57/5 = **11.4**.

### 4Visual

```
FCFS on the running example

| P1        | P2   | P3           | P4      | P5 |
0           8      12             21        26   28

waiting:  P1 0   P2 8-1=7   P3 12-2=10   P4 21-3=18   P5 26-4=22
```

### 5Worked Examples

Example 1 Easy

Same three jobs (24, 3, 3 at time 0) in the order P2, P3, P1. Average waiting time?

Solution

Waits 0, 3, 6 → **3 ms**. Order matters enormously.

Example 2 Medium

P1 arrives at 0 with burst 4, P2 arrives at 6 with burst 3 (FCFS). When does P2 finish? Is the CPU ever idle?

Solution

P1 runs 0–4; the CPU is **idle 4–6**; P2 runs 6–9 → CT = **9**.

Example 3 GATE

In the running example under FCFS, what is the average turnaround time?

Solution

(8 + 11 + 19 + 23 + 24)/5 = **17**.

### 6GATE Traps

⚠️

- TAT = CT − **AT**, not CT alone (unless everyone arrives at 0).
- WT = TAT − BT; for non-pre-emptive schedules it equals start time − AT.
- Leave a gap (idle time) in the Gantt chart if no process has arrived yet.
- Response time and waiting time are equal for non-pre-emptive algorithms, but not for pre-emptive ones.

### 7Memory Hook

🧠

**"Draw the Gantt chart, then TAT = CT − AT, WT = TAT − BT."**

### 8Connect the Dots

FCFS ignores burst lengths, so short jobs suffer. The next lesson runs the **shortest job first**, which gives the smallest average waiting time of all.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**NAT1 markFCFS

Jobs with bursts 24, 3, 3 arrive at time 0 in the order P1, P2, P3 (FCFS). Average waiting time?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT2 marksFCFS

Running example under FCFS: average waiting time?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT2 marksIdle time

FCFS: P1 (AT 0, BT 3), P2 (AT 5, BT 4), P3 (AT 6, BT 2). Average turnaround time?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**MCQ1 markDefinitions

Turnaround time is:

1. (A) completion time − arrival time
2. (B) completion time − burst time
3. (C) burst time + arrival time
4. (D) start time − arrival time

**Q5**MCQ1 markConvoy

The convoy effect is a weakness of:

1. (A) Round robin
2. (B) FCFS
3. (C) SRTF
4. (D) Priority with aging

### 10Rule Card

- AT, BT given; CT from the Gantt chart; TAT = CT − AT; WT = TAT − BT; RT = first start − AT.
- Non-pre-emptive: keep the CPU till done; pre-emptive: can be interrupted.
- FCFS: arrival order, non-pre-emptive, convoy effect; idle gaps when nothing has arrived.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

arrival timeburst timecompletion timeturnaround timewaiting timeresponse timethroughputCPU utilisationGantt chartpre-emptive vs non-pre-emptive schedulingfirst-come first-servedconvoy effectidle time

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. The short-term scheduler.
2. Ready.
3. 2.

#### Self-Test

**Q1** Answer: 171 mark

(0 + 24 + 27)/3.

Re-read: [Lesson 2.1.1](#l-2-1-1) — Scheduling basics: the times we measure; first-come first-served

**Q2** Answer: 11.42 marks

57/5.

Re-read: [Lesson 2.1.1](#l-2-1-1) — Scheduling basics: the times we measure; first-come first-served

**Q3** Answer: 42 marks

P1 0–3 (TAT 3); idle 3–5; P2 5–9 (TAT 4); P3 9–11 (TAT 5): 12/3.

Re-read: [Lesson 2.1.1](#l-2-1-1) — Scheduling basics: the times we measure; first-come first-served

**Q4** Answer: (A)1 mark

Total time in the system.

- **(B) is wrong:** Not meaningful.
- **(C) is wrong:** Not meaningful.
- **(D) is wrong:** That is waiting/response time in non-pre-emptive cases.

Re-read: [Lesson 2.1.1](#l-2-1-1) — Scheduling basics: the times we measure; first-come first-served

**Q5** Answer: (B)1 mark

Short jobs wait behind a long one.

- **(A) is wrong:** Time slices prevent it.
- **(C) is wrong:** Short jobs jump ahead.
- **(D) is wrong:** Not the classic case.

Re-read: [Lesson 2.1.1](#l-2-1-1) — Scheduling basics: the times we measure; first-come first-served

Type next → [**2.1.2** Shortest job first and shortest remaining time first](#l-2-1-2)

## 📄Lesson 2.1.2 — Shortest job first and shortest remaining time first

Phase 2 › CPU Scheduling › Chapter 2.1 Basic scheduling algorithms › Topic 2.1.2

Phase 2Ch 2.1 Basic scheduling algorithmsTopic 2.1.2GATE weight: High≈ 45 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. WT = ? from [Lesson 2.1.1](#l-2-1-1)
2. Which IPC needs explicit synchronization? from [Lesson 1.2.2](#l-1-2-2)
3. Where does a woken (I/O-finished) process go? from [Lesson 1.1.1](#l-1-1-1)

### 1The Hook

🎣

At a photocopier, if someone with one page asks to go before someone with 200, everyone's average wait drops. Always serving the **shortest job first** gives the **smallest average waiting time possible**. Its pre-emptive version, **SRTF**, is the most frequently asked scheduling algorithm in GATE, because tracing it needs care at every arrival.

### 2Predict First

🤔

At time 0, three jobs are waiting with bursts 6, 2 and 4. To make the average wait as small as possible, in what order should they run?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

Shortest first: 2, 4, 6. Waits 0, 2, 6 → average **8/3 ≈ 2.67**. Any other order gives a larger average.

🗣️

In plain words

**SJF**: whenever the CPU becomes free, start the waiting job with the **smallest burst**, and let it finish. **SRTF**: the same idea, but if a new job arrives whose burst is smaller than what the running job still needs, **switch** to the new job immediately.

#### 1. Shortest Job First (SJF), non-pre-emptive

When the CPU is free, pick the arrived process with the smallest burst (ties: earlier arrival). Running example: at 0 only P1 is there → P1 0–8. At 8, ready: P2 (4), P3 (9), P4 (5), P5 (2) → P5 8–10, P2 10–14, P4 14–19, P3 19–28. WT: P1 0, P2 9, P3 17, P4 11, P5 4 → average 41/5 = **8.2**.

#### 2. Shortest Remaining Time First (SRTF), pre-emptive SJF

At **every arrival** (and every completion), run the process with the **smallest remaining time**. Running example:

- t = 0: P1 starts (remaining 8).
- t = 1: P2 arrives with 4 \< 7 → **pre-empt** P1; P2 runs 1–5 (P3, P4, P5 arrive meanwhile but none is shorter than P2's remaining time).
- t = 5: remaining: P1 7, P3 9, P4 5, P5 2 → P5 5–7, then P4 7–12, P1 12–19, P3 19–28.

|  | P1 | P2 | P3 | P4 | P5 |
| --- | --- | --- | --- | --- | --- |
| CT | 19 | 5 | 28 | 12 | 7 |
| TAT | 19 | 4 | 26 | 9 | 3 |
| WT | 11 | 0 | 17 | 4 | 1 |

Average WT = 33/5 = **6.6** (better than SJF's 8.2 and FCFS's 11.4).

#### 3. Properties

- SJF is **optimal** for average waiting time among non-pre-emptive schedules (when all jobs are present); SRTF is optimal among pre-emptive ones.
- **Starvation**: a long job can wait forever if short jobs keep arriving.
- The OS cannot know future bursts. It **predicts** them by **exponential averaging**: **τₙ₊₁ = α·tₙ + (1 − α)·τₙ** (tₙ = last actual burst, τₙ = last prediction, 0 ≤ α ≤ 1).

  α = 0.5, τ₀ = 10, actual bursts 6, 4, 6 → predictions 8, 6, 6.

### 4Visual

```
SRTF on the running example

| P1 | P2      | P5 | P4      | P1             | P3                 |
0    1         5    7         12               19                   28
     ^ P2 (4) beats P1's remaining 7: pre-empt
```

### 5Worked Examples

Example 1 Easy

Bursts 6, 2, 4 at time 0 under SJF. Average turnaround time?

Solution

Run 2, 4, 6: completions 2, 6, 12 → average **20/3 ≈ 6.67**.

Example 2 Medium

Running example under SJF: which process runs right after P1?

Solution

At t = 8 the shortest ready burst is P5's (2): **P5**.

Example 3 GATE

Running example under SRTF: average waiting time?

Solution

**6.6** (see the table).

### 6GATE Traps

⚠️

- In SRTF, re-check at **every arrival**: compare the newcomer's burst with the running job's **remaining** time.
- SJF (non-pre-emptive) never interrupts; a short job arriving just after a long one starts waits.
- Ties go to the earlier arrival (state your rule if the question doesn't).
- SJF/SRTF can starve long jobs.

### 7Memory Hook

🧠

**"Shortest first wins on average; SRTF re-decides at every arrival."**

### 8Connect the Dots

Burst length is one way to rank processes. The next lesson ranks them by **priority**, sees how low-priority processes starve, and fixes it with **aging** and the response-ratio rule.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**NAT2 marksSJF

Running example under SJF (non-pre-emptive): average waiting time?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT2 marksSRTF

Running example under SRTF: average turnaround time?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT2 marksSRTF

Processes (AT, BT): P1 (0, 8), P2 (1, 4), P3 (2, 9), P4 (3, 5). SRTF average waiting time?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**NAT1 markPrediction

Exponential averaging with α = 0.5: previous prediction 10, actual burst 6. Next prediction?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**MCQ1 markOptimality

Which algorithm minimises the average waiting time among non-pre-emptive algorithms (all jobs present at time 0)?

1. (A) Round robin
2. (B) Priority
3. (C) SJF
4. (D) FCFS

### 10Rule Card

- SJF: when free, pick the smallest burst; non-pre-emptive; optimal average WT.
- SRTF: at each arrival/completion, run the smallest remaining time; pre-emptive; optimal among pre-emptive.
- Both can starve long jobs; bursts predicted by τₙ₊₁ = αtₙ + (1 − α)τₙ.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

shortest job firstshortest remaining time firstoptimality for average waiting timestarvationexponential averaging prediction

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. TAT − BT.
2. Shared memory.
3. The Ready queue.

#### Self-Test

**Q1** Answer: 8.22 marks

41/5.

Re-read: [Lesson 2.1.2](#l-2-1-2) — Shortest job first and shortest remaining time first

**Q2** Answer: 12.22 marks

61/5.

Re-read: [Lesson 2.1.2](#l-2-1-2) — Shortest job first and shortest remaining time first

**Q3** Answer: 6.52 marks

Gantt P1 0–1, P2 1–5, P4 5–10, P1 10–17, P3 17–26: waits 9, 0, 15, 2.

Re-read: [Lesson 2.1.2](#l-2-1-2) — Shortest job first and shortest remaining time first

**Q4** Answer: 81 mark

0.5 × 6 + 0.5 × 10.

Re-read: [Lesson 2.1.2](#l-2-1-2) — Shortest job first and shortest remaining time first

**Q5** Answer: (C)1 mark

Shortest first.

- **(A) is wrong:** Pre-emptive, and not optimal for waiting.
- **(B) is wrong:** Depends on priorities.
- **(D) is wrong:** Can be far worse.

Re-read: [Lesson 2.1.2](#l-2-1-2) — Shortest job first and shortest remaining time first

Type next → [**2.1.3** Priority scheduling, starvation and aging; highest response ratio next](#l-2-1-3)

## 📄Lesson 2.1.3 — Priority scheduling, starvation and aging; highest response ratio next

Phase 2 › CPU Scheduling › Chapter 2.1 Basic scheduling algorithms › Topic 2.1.3

Phase 2Ch 2.1 Basic scheduling algorithmsTopic 2.1.3GATE weight: High≈ 40 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. When does SRTF re-decide? from [Lesson 2.1.2](#l-2-1-2)
2. Average WT of the running example under FCFS? from [Lesson 2.1.1](#l-2-1-1)
3. What does fork return in the child? from [Lesson 1.1.2](#l-1-1-2)

### 1The Hook

🎣

In a hospital, a heart attack is treated before a sprained ankle regardless of who came first: **priority scheduling**. But if serious cases keep arriving, the sprained ankle may wait forever. The cure is **aging**: the longer you wait, the more important you become. GATE asks traces of both versions and the **response ratio** formula that builds aging in.

### 2Predict First

🤔

Priority scheduling (lower number = more important). A priority-5 job has waited 2 hours while priority-1 jobs keep arriving. What happens without any fix?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

It may **never** run: **starvation**. Aging raises its priority over time so it eventually runs.

🗣️

In plain words

Each process has a priority number; the scheduler always picks the most important ready process. In the **pre-emptive** version, a more important arrival interrupts the running one. To stop unimportant processes waiting forever, increase their importance as they wait (**aging**), or use a ratio that grows with waiting time (**HRRN**).

#### 1. Priority scheduling

- Convention here: **smaller number = higher priority** (questions always say).
- **Non-pre-emptive**: when the CPU is free, run the highest-priority ready process to completion.
- **Pre-emptive**: if a higher-priority process arrives, pre-empt the running one.
- SJF is priority scheduling with priority = burst length.

Running example (priorities P1 3, P2 1, P3 4, P4 2, P5 5):

- **Non-pre-emptive**: P1 0–8 (only one there), then P2 8–12, P4 12–17, P3 17–26, P5 26–28. Average WT = 53/5 = **10.6**.
- **Pre-emptive**: P1 0–1, P2 (priority 1) pre-empts: 1–5, then P4 5–10, P1 10–17, P3 17–26, P5 26–28. Average WT = 48/5 = **9.6**.

#### 2. Starvation and aging

Low-priority processes may wait indefinitely. **Aging**: gradually increase the priority of processes that wait long (e.g. +1 every 15 minutes).

#### 3. Highest Response Ratio Next (HRRN)

Non-pre-emptive. When the CPU is free, compute for each ready process **response ratio = (waiting time + burst time) / burst time**, and pick the **largest**. Short jobs get high ratios quickly, but long jobs' ratios grow while they wait, so nobody starves. Running example at t = 8 (after P1): P2 (7 + 4)/4 = 2.75, P3 (6 + 9)/9 ≈ 1.67, P4 (5 + 5)/5 = 2, P5 (4 + 2)/2 = **3** → P5 next. Then at t = 10: P2 (9 + 4)/4 = 3.25, P3 (8 + 9)/9 ≈ 1.89, P4 (7 + 5)/5 = 2.4 → P2.

### 4Visual

```
Pre-emptive priority on the running example (smaller = higher)

| P1 | P2 (1)  | P4 (2)    | P1 (3)        | P3 (4)            | P5 |
0    1         5           10              17                  26   28
```

| Algorithm | Avg WT on the running example |
| --- | --- |
| FCFS | 11.4 |
| SJF | 8.2 |
| SRTF | 6.6 |
| Priority (non-pre-emptive) | 10.6 |
| Priority (pre-emptive) | 9.6 |
| HRRN | 8.2 |

### 5Worked Examples

Example 1 Easy

All arrive at 0: P1 (BT 10, pr 3), P2 (1, 1), P3 (2, 4), P4 (1, 5), P5 (5, 2). Non-pre-emptive priority order?

Solution

P2, P5, P1, P3, P4.

Example 2 Medium

Average waiting time for the Easy example?

Solution

Order P2 0–1, P5 1–6, P1 6–16, P3 16–18, P4 18–19. Waits: P1 6, P2 0, P3 16, P4 18, P5 1 → 41/5 = **8.2**.

Example 3 GATE

HRRN: at time 20 the CPU is free. Ready: A (waiting 10, burst 5), B (waiting 6, burst 2). Which runs?

Solution

A: 15/5 = 3; B: 8/2 = **4** → **B**.

### 6GATE Traps

⚠️

- Check which way the priority numbers go (small = high is common, not universal).
- Pre-emptive priority re-decides at every arrival, like SRTF.
- HRRN is **non-pre-emptive**; the ratio uses waiting time **so far**.
- Aging fixes starvation; it is not an algorithm on its own.

### 7Memory Hook

🧠

**"Most important first; age the forgotten; HRRN = (wait + burst)/burst."**

### 8Connect the Dots

Chapter 2.1 is complete. None of these algorithms guarantees every process a quick turn. Chapter 2.2 introduces **round robin**, the basis of time-sharing, where each process gets the CPU for a small slice in turn.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**NAT2 marksPriority

Running example under non-pre-emptive priority: average waiting time?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT2 marksPre-emptive priority

Running example under pre-emptive priority: completion time of P1?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT2 marksPriority, all at 0

All arrive at 0: P1 (BT 10, pr 3), P2 (1, 1), P3 (2, 4), P4 (1, 5), P5 (5, 2). Non-pre-emptive priority: average waiting time?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**NAT1 markResponse ratio

A process has waited 12 ms and needs 4 ms. Its response ratio?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**MCQ1 markStarvation

Which technique prevents starvation in priority scheduling?

1. (A) Pre-emption
2. (B) FCFS tie-breaking
3. (C) A larger time quantum
4. (D) Aging

### 10Rule Card

- Priority: pick the most important ready process (state the direction of numbers); non-pre-emptive or pre-emptive.
- Starvation of low priorities; aging raises priority over time.
- HRRN: non-pre-emptive; pick the largest (W + S)/S; no starvation.
- SJF = priority by burst length.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

priority schedulingpre-emptive and non-pre-emptive prioritystarvationaginghighest response ratio nextresponse ratio

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. At every arrival and completion.
2. 11.4.
3. 0.

#### Self-Test

**Q1** Answer: 10.62 marks

53/5.

Re-read: [Lesson 2.1.3](#l-2-1-3) — Priority scheduling, starvation and aging; highest response ratio next

**Q2** Answer: 172 marks

P1 0–1, then 10–17.

Re-read: [Lesson 2.1.3](#l-2-1-3) — Priority scheduling, starvation and aging; highest response ratio next

**Q3** Answer: 8.22 marks

41/5.

Re-read: [Lesson 2.1.3](#l-2-1-3) — Priority scheduling, starvation and aging; highest response ratio next

**Q4** Answer: 41 mark

(12 + 4)/4.

Re-read: [Lesson 2.1.3](#l-2-1-3) — Priority scheduling, starvation and aging; highest response ratio next

**Q5** Answer: (D)1 mark

Raise priority with waiting time.

- **(A) is wrong:** Can make starvation worse.
- **(B) is wrong:** Doesn't help the lowest priorities.
- **(C) is wrong:** Unrelated.

Re-read: [Lesson 2.1.3](#l-2-1-3) — Priority scheduling, starvation and aging; highest response ratio next

Type next → [**LI-2.1** Chapter 2.1 Lock-in](#l-LI-2-1)

## 🔒Chapter 2.1 Lock-in — Basic scheduling algorithms

Phase 2 › CPU Scheduling › Chapter 2.1 Basic scheduling algorithms

Phase 2Ch 2.1 Basic scheduling algorithms

### ACompressed recap

🧾

TAT = CT − AT; WT = TAT − BT; RT = first start − AT. FCFS (convoy effect, idle gaps). SJF (non-pre-emptive, optimal average WT), SRTF (re-decide at every arrival), exponential averaging τₙ₊₁ = αtₙ + (1 − α)τₙ. Priority (both kinds), starvation, aging; HRRN (W + S)/S. Running example averages: FCFS 11.4, SJF 8.2, SRTF 6.6, priority 10.6 / 9.6.

### BMerged rule card

[2.1.1](#l-2-1-1) Scheduling basics: the times we measure; first-come first-served

- AT, BT given; CT from the Gantt chart; TAT = CT − AT; WT = TAT − BT; RT = first start − AT.
- Non-pre-emptive: keep the CPU till done; pre-emptive: can be interrupted.
- FCFS: arrival order, non-pre-emptive, convoy effect; idle gaps when nothing has arrived.

[2.1.2](#l-2-1-2) Shortest job first and shortest remaining time first

- SJF: when free, pick the smallest burst; non-pre-emptive; optimal average WT.
- SRTF: at each arrival/completion, run the smallest remaining time; pre-emptive; optimal among pre-emptive.
- Both can starve long jobs; bursts predicted by τₙ₊₁ = αtₙ + (1 − α)τₙ.

[2.1.3](#l-2-1-3) Priority scheduling, starvation and aging; highest response ratio next

- Priority: pick the most important ready process (state the direction of numbers); non-pre-emptive or pre-emptive.
- Starvation of low priorities; aging raises priority over time.
- HRRN: non-pre-emptive; pick the largest (W + S)/S; no starvation.
- SJF = priority by burst length.

### CInterleaved GATE-style questions

**Q1**NAT2 marksFCFS

FCFS: P1 (AT 0, BT 5), P2 (AT 1, BT 3), P3 (AT 2, BT 8), P4 (AT 3, BT 6). Average waiting time?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT1 markResponse time

Running example under FCFS: response time of P4?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT2 marksSJF

SJF (non-pre-emptive): P1 (AT 0, BT 7), P2 (AT 2, BT 4), P3 (AT 4, BT 1), P4 (AT 5, BT 4). Average waiting time?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**NAT2 marksSRTF

SRTF: P1 (AT 0, BT 7), P2 (AT 2, BT 4), P3 (AT 4, BT 1), P4 (AT 5, BT 4). Average waiting time?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**NAT1 markPrediction

α = 0.25, previous prediction 16, actual burst 8. Next prediction?

Numerical answer: \_\_\_\_\_\_\_\_

**Q6**MCQ1 markPre-emption

Which of these is pre-emptive?

1. (A) SRTF
2. (B) HRRN
3. (C) SJF
4. (D) FCFS

**Q7**NAT2 marksHRRN

At time 10 the CPU is free. Ready: X (arrived 2, burst 4), Y (arrived 6, burst 1), Z (arrived 0, burst 8). Largest response ratio?

Numerical answer: \_\_\_\_\_\_\_\_

**Q8**MCQ1 markPriority

SJF can be viewed as priority scheduling where priority is based on:

1. (A) process ID
2. (B) predicted CPU burst
3. (C) arrival time
4. (D) memory size

### DAnswer Vault

🔐 Open the Answer Vault

**Q1** Answer: 5.752 marks

Starts 0, 5, 8, 16: waits 0, 4, 6, 13.

Re-read: [Lesson 2.1.1](#l-2-1-1) — Scheduling basics: the times we measure; first-come first-served

**Q2** Answer: 181 mark

Starts at 21, arrived at 3.

Re-read: [Lesson 2.1.1](#l-2-1-1) — Scheduling basics: the times we measure; first-come first-served

**Q3** Answer: 42 marks

P1 0–7, P3 7–8, P2 8–12, P4 12–16: waits 0, 6, 3, 7.

Re-read: [Lesson 2.1.2](#l-2-1-2) — Shortest job first and shortest remaining time first

**Q4** Answer: 32 marks

P1 0–2, P2 2–4, P3 4–5, P2 5–7, P4 7–11, P1 11–16: waits 9, 1, 0, 2.

Re-read: [Lesson 2.1.2](#l-2-1-2) — Shortest job first and shortest remaining time first

**Q5** Answer: 141 mark

0.25 × 8 + 0.75 × 16.

Re-read: [Lesson 2.1.2](#l-2-1-2) — Shortest job first and shortest remaining time first

**Q6** Answer: (A)1 mark

It interrupts on shorter arrivals.

- **(B) is wrong:** Non-pre-emptive.
- **(C) is wrong:** Non-pre-emptive.
- **(D) is wrong:** Non-pre-emptive.

Re-read: [Lesson 2.1.2](#l-2-1-2) — Shortest job first and shortest remaining time first

**Q7** Answer: 52 marks

X (8 + 4)/4 = 3; Y (4 + 1)/1 = 5; Z (10 + 8)/8 = 2.25.

Re-read: [Lesson 2.1.3](#l-2-1-3) — Priority scheduling, starvation and aging; highest response ratio next

**Q8** Answer: (B)1 mark

Shorter burst = higher priority.

- **(A) is wrong:** Arbitrary.
- **(C) is wrong:** That is FCFS.
- **(D) is wrong:** Unrelated.

Re-read: [Lesson 2.1.3](#l-2-1-3) — Priority scheduling, starvation and aging; highest response ratio next

Type next → [**2.2.1** Round robin and the time quantum](#l-2-2-1)

## 📄Lesson 2.2.1 — Round robin and the time quantum

Phase 2 › CPU Scheduling › Chapter 2.2 Time sharing and beyond › Topic 2.2.1

Phase 2Ch 2.2 Time sharing and beyondTopic 2.2.1GATE weight: High≈ 45 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. HRRN ratio? from [Lesson 2.1.3](#l-2-1-3)
2. SRTF average WT on the running example? from [Lesson 2.1.2](#l-2-1-2)
3. Which state does a pre-empted process go to? from [Lesson 1.1.1](#l-1-1-1)

### 1The Hook

🎣

In a game of carrom with four players, each takes one turn, then the next player goes; nobody waits more than three turns. **Round robin** (RR) gives every ready process a small **time quantum** in turn. It is how time-sharing systems feel responsive, and GATE asks you to trace it: who runs when, how many context switches, which completion time.

### 2Predict First

🤔

Three processes, all at time 0, need 5, 3 and 1 ms. RR with quantum 2. In what order do they finish?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

P1 0–2, P2 2–4, P3 4–5 (done), P1 5–7, P2 7–8 (done), P1 8–9 (done). Finish order: **P3, P2, P1**.

🗣️

In plain words

Keep a queue of ready processes. Give the front process the CPU for at most **q** milliseconds. If it finishes, good; if not, it goes to the **back** of the queue. New arrivals also join the back. Repeat.

#### 1. The rules (these notes' conventions)

1. The ready queue is FIFO.
2. The front process runs for **min(q, remaining time)**.
3. Processes that **arrive** during that slice join the back of the queue as they arrive.
4. If the running process is not finished, it joins the back **after** any process that arrived at the same instant.

#### 2. Running example with q = 4

- 0–4 P1 (P2, P3, P4, P5 arrive at 1, 2, 3, 4; P1 rejoins after P5).
- Queue: P2, P3, P4, P5, P1 → P2 4–8 (done), P3 8–12, P4 12–16, P5 16–18 (done), P1 18–22 (done), P3 22–26, P4 26–27 (done), P3 27–28 (done).

|  | P1 | P2 | P3 | P4 | P5 |
| --- | --- | --- | --- | --- | --- |
| CT | 22 | 8 | 28 | 27 | 18 |
| WT | 14 | 3 | 17 | 19 | 12 |

Average WT = 65/5 = **13**; average response time = (0 + 3 + 6 + 9 + 12)/5 = **6**. RR usually has a **worse** average waiting time than SJF but a much better **response time**: everyone starts soon.

#### 3. Choosing the quantum

- **q very large** → RR becomes **FCFS**.
- **q very small** → many context switches: overhead dominates.
- With context-switch time s, the fraction of time doing useful work is about **q/(q + s)** (q = 4, s = 1 → 80%).
- With n processes in the queue, each waits at most **(n − 1)·q** before its next turn.
- Rule of thumb: about 80% of CPU bursts should be shorter than q.

#### 4. Counting context switches

Count changes from one process to a **different** one in the Gantt chart (the very first dispatch is not usually counted; a process continuing after its own slice because nobody else is waiting is not a switch). Running example, q = 4: P1→P2→P3→P4→P5→P1→P3→P4→P3: **8** switches.

### 4Visual

```
Round robin, q = 4, running example

| P1  | P2  | P3  | P4  | P5 | P1  | P3  | P4 | P3 |
0     4     8     12    16   18    22    26   27   28
      ^ P5 arrived at 4, so it queues before the pre-empted P1
```

### 5Worked Examples

Example 1 Easy

All at 0, bursts 24, 3, 3, RR with q = 4. Average waiting time?

Solution

P1 0–4, P2 4–7, P3 7–10, P1 10–30: waits 6, 4, 7 → **17/3 ≈ 5.67**.

Example 2 Medium

Running example with q = 2: completion time of P5?

Solution

Trace: P1 0–2, P2 2–4, P3 4–6, P1 6–8, P4 8–10, P5 10–12 → **12**.

Example 3 GATE

A system uses RR with q = 10 ms and a context switch costs 2 ms. What fraction of CPU time is useful (all bursts long)?

Solution

10/(10 + 2) ≈ **0.833**.

### 6GATE Traps

⚠️

- A newly arrived process and a just-pre-empted one at the same instant: the arrival goes first (state the rule you use).
- When a process finishes before its quantum ends, the next process starts immediately.
- q → ∞ makes RR into FCFS, not SJF.
- Count context switches between **different** processes only.

### 7Memory Hook

🧠

**"Run q, back of the line; new arrivals queue first."**

### 8Connect the Dots

Real systems mix many kinds of processes (interactive, batch, system) and processes alternate CPU work with I/O waits. The last scheduling lesson covers **multilevel queues** and how to handle **CPU and I/O bursts** together.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**NAT2 marksRR

Running example, RR with q = 4: average waiting time?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT2 marksRR

Running example, RR with q = 2: completion time of P1?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT1 markRR

All at 0 with bursts 5, 3, 1, RR with q = 2. Completion time of P2?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**NAT2 marksContext switches

Running example, RR with q = 3: number of context switches (changes between different processes; the first dispatch not counted)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**MCQ1 markLarge quantum

If the time quantum is larger than every burst, round robin behaves like:

1. (A) SRTF
2. (B) SJF
3. (C) FCFS
4. (D) Priority

### 10Rule Card

- RR: FIFO ready queue; run min(q, remaining); unfinished → back; arrivals at the same instant queue before the pre-empted process.
- Large q → FCFS; small q → overhead; useful fraction q/(q + s); max wait between turns (n − 1)q.
- RR: worse average WT than SJF, better response time.
- Context switches: count changes between different processes.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

round robintime quantumready-queue order rulestime-sharingresponse time vs waiting timequantum size trade-offcontext-switch overhead q/(q + s)counting context switches

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. (waiting + burst)/burst.
2. 6.6.
3. Ready.

#### Self-Test

**Q1** Answer: 132 marks

65/5.

Re-read: [Lesson 2.2.1](#l-2-2-1) — Round robin and the time quantum

**Q2** Answer: 242 marks

Trace the queue: P1 runs 0–2, 6–8, 16–18, 22–24.

Re-read: [Lesson 2.2.1](#l-2-2-1) — Round robin and the time quantum

**Q3** Answer: 81 mark

P1 0–2, P2 2–4, P3 4–5, P1 5–7, P2 7–8.

Re-read: [Lesson 2.2.1](#l-2-2-1) — Round robin and the time quantum

**Q4** Answer: 102 marks

P1 P2 P3 P4 P1 P5 P2 P3 P4 P1 P3.

Re-read: [Lesson 2.2.1](#l-2-2-1) — Round robin and the time quantum

**Q5** Answer: (C)1 mark

Each process finishes in its first turn, in queue order.

- **(A) is wrong:** No pre-emption happens.
- **(B) is wrong:** Order is by arrival, not length.
- **(D) is wrong:** Unrelated.

Re-read: [Lesson 2.2.1](#l-2-2-1) — Round robin and the time quantum

Type next → [**2.2.2** Multilevel queues, CPU and I/O bursts, CPU utilisation](#l-2-2-2)

## 📄Lesson 2.2.2 — Multilevel queues, CPU and I/O bursts, CPU utilisation

Phase 2 › CPU Scheduling › Chapter 2.2 Time sharing and beyond › Topic 2.2.2

Phase 2Ch 2.2 Time sharing and beyondTopic 2.2.2GATE weight: Medium≈ 40 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. RR with a huge quantum behaves like? from [Lesson 2.2.1](#l-2-2-1)
2. SRTF re-decides when? from [Lesson 2.1.2](#l-2-1-2)
3. Which scheduler admits jobs (degree of multiprogramming)? from [Lesson 1.1.2](#l-1-1-2)

### 1The Hook

🎣

A real computer runs keyboard handlers, a video call, a compiler and a backup at the same time: very different needs. One queue can't suit them all, so operating systems use **several queues** with different rules. And processes don't just compute: they alternate between CPU bursts and I/O waits. GATE's harder scheduling questions mix both: "processes do I/O, then compute, then I/O; find the CPU idle time".

### 2Predict First

🤔

A process does I/O for 2 ms, computes for 7 ms, then does I/O for 1 ms. While it does I/O, can another process use the CPU?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

**Yes.** During I/O the process is Waiting and needs no CPU; the scheduler gives the CPU to someone else. That overlap is the whole point of multiprogramming.

🗣️

In plain words

Split processes into classes, each with its own queue and its own scheduling rule, and decide between queues by priority or time-sharing (**multilevel queues**). Let processes **move** between queues according to how they behave (**multilevel feedback queue**). When processes alternate CPU and I/O, schedule only the CPU parts; the I/O parts run at the same time on the devices.

#### 1. Multilevel queue

- Fixed classes: e.g. system, interactive (foreground, RR), batch (background, FCFS).
- Between queues: **fixed priority** (a lower queue runs only when all higher ones are empty: starvation possible) or **time slicing** (e.g. 80% of CPU time to foreground, 20% to background).
- A process stays in its queue forever.

#### 2. Multilevel feedback queue (MLFQ)

- Processes **move** between queues.
- New processes start in the top queue (small quantum, e.g. 8 ms). If a process uses its whole quantum, it is **demoted** to the next queue (larger quantum, e.g. 16 ms), and the bottom queue may be FCFS.
- Short, interactive processes finish quickly at the top; long CPU-bound ones sink. **Aging** (promotion after long waits) prevents starvation.
- Most flexible and most complex: defined by the number of queues, each queue's algorithm, and the promotion/demotion rules.

#### 3. CPU and I/O bursts together

A process alternates **CPU burst → I/O burst → CPU burst …**. Rules for questions: only the CPU bursts compete for the CPU; each process does its I/O on its own device in parallel; when its I/O ends it rejoins the ready queue. **Classic example** (pre-emptive shortest-remaining-CPU-burst): three processes arrive at 0 with total times 10, 20, 30; each spends the first 20% on I/O, the next 70% computing, the last 10% on I/O.

- A: I/O 0–2, CPU 2–9, I/O 9–10.
- B: I/O 0–4, ready at 4 (needs 14) but A has less left → CPU 9–23, I/O 23–25.
- C: I/O 0–6, CPU 23–44, I/O 44–47.
- CPU idle: 0–2 and 44–47 = 5 of 47 → **10.6%** idle.

#### 4. CPU utilisation from I/O probability

If each of n processes spends a fraction p of its time waiting for I/O (independently), the CPU is idle only when **all** wait: **utilisation ≈ 1 − pⁿ**. p = 0.8, n = 4 → 1 − 0.4096 ≈ **59%**.

### 4Visual

A multilevel feedback queue: CPU-hungry processes sink; long-waiting ones can be promoted back up.

```
CPU + I/O example (shortest remaining CPU burst first)

time:  0   2         9 10            23     44  47
CPU : [idle][   A    ][      B      ][    C    ][idle]
A   :  I/O   CPU      I/O
B   :  I/O(0-4) waits    CPU            I/O
C   :  I/O(0-6) waits ............ CPU            I/O
```

### 5Worked Examples

Example 1 Easy

In a multilevel queue with fixed priority, can a batch process starve?

Solution

**Yes**, if the higher-priority queues are never empty.

Example 2 Medium

In an MLFQ with quanta 8 and 16 (then FCFS), a process needs 30 ms of CPU. How much does it get in each queue?

Solution

8 in queue 0, 16 in queue 1, the remaining **6 in queue 2**.

Example 3 GATE

4 processes each wait for I/O 70% of the time (independently). Approximate CPU utilisation?

Solution

1 − 0.7⁴ = 1 − 0.2401 ≈ **0.76**.

### 6GATE Traps

⚠️

- Multilevel **queue**: processes never move; multilevel **feedback** queue: they move.
- I/O bursts run in parallel with other processes' CPU bursts.
- Count CPU idle time at the start (everyone doing I/O) and at the end (last process doing its final I/O).
- 1 − pⁿ assumes independent processes; p is the I/O-wait fraction, not the CPU fraction.

### 7Memory Hook

🧠

**"Different queues for different jobs; feedback lets jobs sink or rise; I/O overlaps CPU."**

### 8Connect the Dots

Phase 2 is complete. When processes share data, the order in which the scheduler interleaves them can corrupt that data. Phase 3, **synchronization**, is about preventing that.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**NAT2 marksCPU idle

Three processes arrive at 0 with total times 10, 20, 30; each spends the first 20% on I/O, the next 70% on CPU, the last 10% on I/O (pre-emptive shortest remaining CPU burst). Percentage of time the CPU is idle (1 decimal)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT2 marksUtilisation

5 processes each wait for I/O 60% of the time. Approximate CPU utilisation (3 decimals)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT2 marksCPU + I/O

FCFS for the CPU, separate I/O devices. P1 (AT 0): CPU 3, I/O 4, CPU 2. P2 (AT 0): CPU 2, I/O 5, CPU 1. P3 (AT 1): CPU 4, I/O 1, CPU 3. When does P3 finish?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**MCQ1 markMLFQ

In a multilevel feedback queue, a process that keeps using its full quantum is usually:

1. (A) promoted
2. (B) moved to the Waiting state
3. (C) terminated
4. (D) demoted to a lower-priority queue

**Q5**MCQ1 markMultilevel queue

The key difference between a multilevel queue and a multilevel feedback queue is that in the feedback version:

1. (A) processes can move between queues
2. (B) every queue uses FCFS
3. (C) there is only one queue
4. (D) there is no pre-emption

### 10Rule Card

- Multilevel queue: fixed classes, fixed priority or time-sliced between queues; no movement.
- MLFQ: start at the top; full quantum used → demote; aging → promote; defined by queues, algorithms, move rules.
- CPU/I/O bursts: only CPU bursts compete; I/O overlaps; count idle at the start and end.
- Utilisation ≈ 1 − pⁿ.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

multilevel queue schedulingforeground and background queuesfixed-priority vs time-sliced queuesmultilevel feedback queuedemotion and promotionCPU and I/O burstsoverlapping I/O with computationCPU idle timeCPU utilisation 1 − pⁿ

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. FCFS.
2. At every arrival and completion.
3. Long-term.

#### Self-Test

**Q1** Answer: 10.5 to 10.72 marks

Idle 5 of 47.

Re-read: [Lesson 2.2.2](#l-2-2-2) — Multilevel queues, CPU and I/O bursts, CPU utilisation

**Q2** Answer: 0.921 to 0.9232 marks

1 − 0.6⁵.

Re-read: [Lesson 2.2.2](#l-2-2-2) — Multilevel queues, CPU and I/O bursts, CPU utilisation

**Q3** Answer: 152 marks

CPU: P1 0–3, P2 3–5, P3 5–9, P1 9–11, P2 11–12, P3 12–15.

Re-read: [Lesson 2.2.2](#l-2-2-2) — Multilevel queues, CPU and I/O bursts, CPU utilisation

**Q4** Answer: (D)1 mark

CPU-bound processes sink.

- **(A) is wrong:** Promotion is for long waiting (aging).
- **(B) is wrong:** Only I/O makes it wait.
- **(C) is wrong:** No.

Re-read: [Lesson 2.2.2](#l-2-2-2) — Multilevel queues, CPU and I/O bursts, CPU utilisation

**Q5** Answer: (A)1 mark

Movement based on behaviour.

- **(B) is wrong:** Queues may use RR.
- **(C) is wrong:** Several queues.
- **(D) is wrong:** Pre-emption is common.

Re-read: [Lesson 2.2.2](#l-2-2-2) — Multilevel queues, CPU and I/O bursts, CPU utilisation

Type next → [**LI-2.2** Chapter 2.2 Lock-in](#l-LI-2-2)

## 🔒Chapter 2.2 Lock-in — Time sharing and beyond

Phase 2 › CPU Scheduling › Chapter 2.2 Time sharing and beyond

Phase 2Ch 2.2 Time sharing and beyond

### ACompressed recap

🧾

RR: FIFO queue, run min(q, remaining), arrivals at the same instant before the pre-empted process; large q → FCFS; useful fraction q/(q + s); count switches between different processes. Multilevel queues (fixed classes) vs MLFQ (demote on full quantum, aging promotes). CPU/I/O mixes: only CPU bursts compete, I/O overlaps; idle at the start and end; utilisation 1 − pⁿ.

### BMerged rule card

[2.2.1](#l-2-2-1) Round robin and the time quantum

- RR: FIFO ready queue; run min(q, remaining); unfinished → back; arrivals at the same instant queue before the pre-empted process.
- Large q → FCFS; small q → overhead; useful fraction q/(q + s); max wait between turns (n − 1)q.
- RR: worse average WT than SJF, better response time.
- Context switches: count changes between different processes.

[2.2.2](#l-2-2-2) Multilevel queues, CPU and I/O bursts, CPU utilisation

- Multilevel queue: fixed classes, fixed priority or time-sliced between queues; no movement.
- MLFQ: start at the top; full quantum used → demote; aging → promote; defined by queues, algorithms, move rules.
- CPU/I/O bursts: only CPU bursts compete; I/O overlaps; count idle at the start and end.
- Utilisation ≈ 1 − pⁿ.

### CInterleaved GATE-style questions

**Q1**NAT2 marksRR

All at 0 with bursts 24, 3, 3; RR with q = 4. Average waiting time (2 decimals)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT2 marksRR

RR with q = 3: P1 (AT 0, BT 5), P2 (AT 1, BT 3), P3 (AT 2, BT 1). Completion time of P1?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT1 markOverhead

q = 20 ms, context switch 5 ms. Fraction of CPU time spent on useful work?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**MCQ1 markResponse

Compared with SJF, round robin generally gives:

1. (A) better average waiting time
2. (B) fewer context switches
3. (C) better response time
4. (D) starvation of short jobs

**Q5**NAT1 markBound

RR with q = 10 ms and 6 processes always in the queue. Longest wait between two consecutive turns of one process?

Numerical answer: \_\_\_\_\_\_\_\_

**Q6**NAT2 marksUtilisation

3 processes each wait for I/O 50% of the time. CPU utilisation?

Numerical answer: \_\_\_\_\_\_\_\_

**Q7**MCQ1 markStarvation

In a multilevel queue with fixed priority between queues, starvation can affect:

1. (A) the highest-priority queue
2. (B) no queue
3. (C) only I/O-bound processes
4. (D) the lowest-priority queue

**Q8**NAT2 marksMLFQ

MLFQ with quanta 4 and 8 in the top two queues, then FCFS. A process needs 25 ms of CPU. How many ms does it run in the FCFS queue?

Numerical answer: \_\_\_\_\_\_\_\_

### DAnswer Vault

🔐 Open the Answer Vault

**Q1** Answer: 5.66 to 5.672 marks

(6 + 4 + 7)/3.

Re-read: [Lesson 2.2.1](#l-2-2-1) — Round robin and the time quantum

**Q2** Answer: 92 marks

P1 0–3, P2 3–6, P3 6–7, P1 7–9.

Re-read: [Lesson 2.2.1](#l-2-2-1) — Round robin and the time quantum

**Q3** Answer: 0.81 mark

20/25.

Re-read: [Lesson 2.2.1](#l-2-2-1) — Round robin and the time quantum

**Q4** Answer: (C)1 mark

Everyone gets a turn soon.

- **(A) is wrong:** Usually worse.
- **(B) is wrong:** More switches.
- **(D) is wrong:** No starvation in RR.

Re-read: [Lesson 2.2.1](#l-2-2-1) — Round robin and the time quantum

**Q5** Answer: 501 mark

(n − 1)q.

Re-read: [Lesson 2.2.1](#l-2-2-1) — Round robin and the time quantum

**Q6** Answer: 0.8752 marks

1 − 0.5³.

Re-read: [Lesson 2.2.2](#l-2-2-2) — Multilevel queues, CPU and I/O bursts, CPU utilisation

**Q7** Answer: (D)1 mark

Lower queues run only when higher ones are empty.

- **(A) is wrong:** Always served first.
- **(B) is wrong:** It can happen.
- **(C) is wrong:** Not specific to I/O-bound.

Re-read: [Lesson 2.2.2](#l-2-2-2) — Multilevel queues, CPU and I/O bursts, CPU utilisation

**Q8** Answer: 132 marks

25 − 4 − 8.

Re-read: [Lesson 2.2.2](#l-2-2-2) — Multilevel queues, CPU and I/O bursts, CPU utilisation

Type next → [**CP-2** Phase 2 Checkpoint (15 questions)](#l-CP-2)

## ⏱️Phase 2 Checkpoint — CPU Scheduling

Phase 2 › CPU Scheduling

Phase 2

Phase 2 Checkpoint: 15 questions on CPU scheduling.

⏱️

**15 questions · 23 marks · 45 minutes.** Negative marking on MCQ only: −1/3 mark for a wrong 1-mark MCQ, −2/3 for a wrong 2-mark MCQ. No negative marking for MSQ or NAT; MSQ has no partial credit.

**Q1**NAT1 markFormulas

A process arrives at 3, needs 5 ms of CPU and completes at 20. Waiting time?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT2 marksFCFS

Running example (P1 0/8, P2 1/4, P3 2/9, P4 3/5, P5 4/2) under FCFS: completion time of P4?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**MCQ1 markMetric

For an interactive system, the most important metric is usually:

1. (A) throughput
2. (B) response time
3. (C) turnaround time of batch jobs
4. (D) disk utilisation

**Q4**NAT2 marksSJF

All arrive at 0 with bursts 6, 8, 7, 3 (SJF). Average waiting time?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**NAT2 marksSRTF

Running example under SRTF: waiting time of P1?

Numerical answer: \_\_\_\_\_\_\_\_

**Q6**NAT2 marksSRTF

SRTF: P1 (AT 0, BT 9), P2 (AT 1, BT 4), P3 (AT 2, BT 9). Average turnaround time (2 decimals)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q7**NAT1 markPrediction

α = 0.5, τ₀ = 10, actual bursts 6 then 4. Prediction τ₂?

Numerical answer: \_\_\_\_\_\_\_\_

**Q8**NAT2 marksPriority

Running example under pre-emptive priority: average waiting time?

Numerical answer: \_\_\_\_\_\_\_\_

**Q9**NAT1 markHRRN

A job waited 9 ms and needs 3 ms. Response ratio?

Numerical answer: \_\_\_\_\_\_\_\_

**Q10**MCQ1 markStarvation

Which algorithm can NOT cause starvation?

1. (A) Round robin
2. (B) SRTF
3. (C) Priority without aging
4. (D) SJF

**Q11**NAT2 marksRR

Running example, RR with q = 4: average response time?

Numerical answer: \_\_\_\_\_\_\_\_

**Q12**NAT2 marksRR

Running example, RR with q = 3: completion time of P2?

Numerical answer: \_\_\_\_\_\_\_\_

**Q13**MCQ1 markQuantum

Making the time quantum very small mainly increases:

1. (A) starvation
2. (B) the convoy effect
3. (C) throughput
4. (D) context-switch overhead

**Q14**NAT2 marksCPU + I/O

Two processes arrive at 0 (FCFS on the CPU, separate I/O devices). A: CPU 4, I/O 6, CPU 2. B: CPU 3, I/O 2, CPU 3. Total CPU idle time until both finish?

Numerical answer: \_\_\_\_\_\_\_\_

**Q15**NAT1 markUtilisation

2 processes each wait for I/O 90% of the time. CPU utilisation?

Numerical answer: \_\_\_\_\_\_\_\_

### ✓Answer Vault

🔐 Open the Answer Vault

**Q1** Answer: 121 mark

TAT 17 − BT 5.

Re-read: [Lesson 2.1.1](#l-2-1-1) — Scheduling basics: the times we measure; first-come first-served

**Q2** Answer: 262 marks

P1 0–8, P2 8–12, P3 12–21, P4 21–26.

Re-read: [Lesson 2.1.1](#l-2-1-1) — Scheduling basics: the times we measure; first-come first-served

**Q3** Answer: (B)1 mark

Users notice how soon something happens.

- **(A) is wrong:** Batch-oriented.
- **(C) is wrong:** Batch-oriented.
- **(D) is wrong:** Not a CPU-scheduling metric.

Re-read: [Lesson 2.1.1](#l-2-1-1) — Scheduling basics: the times we measure; first-come first-served

**Q4** Answer: 72 marks

Order 3, 6, 7, 8: waits 0, 3, 9, 16.

Re-read: [Lesson 2.1.2](#l-2-1-2) — Shortest job first and shortest remaining time first

**Q5** Answer: 112 marks

TAT 19 − BT 8.

Re-read: [Lesson 2.1.2](#l-2-1-2) — Shortest job first and shortest remaining time first

**Q6** Answer: 12.33 to 12.342 marks

P1 0–1, P2 1–5, P1 5–13, P3 13–22: TAT 13, 4, 20 → 37/3.

Re-read: [Lesson 2.1.2](#l-2-1-2) — Shortest job first and shortest remaining time first

**Q7** Answer: 61 mark

τ₁ = 8; τ₂ = 0.5 × 4 + 0.5 × 8.

Re-read: [Lesson 2.1.2](#l-2-1-2) — Shortest job first and shortest remaining time first

**Q8** Answer: 9.62 marks

48/5.

Re-read: [Lesson 2.1.3](#l-2-1-3) — Priority scheduling, starvation and aging; highest response ratio next

**Q9** Answer: 41 mark

12/3.

Re-read: [Lesson 2.1.3](#l-2-1-3) — Priority scheduling, starvation and aging; highest response ratio next

**Q10** Answer: (A)1 mark

Every process gets a turn.

- **(B) is wrong:** Long jobs can starve.
- **(C) is wrong:** Low priorities can starve.
- **(D) is wrong:** Long jobs can starve.

Re-read: [Lesson 2.1.3](#l-2-1-3) — Priority scheduling, starvation and aging; highest response ratio next

**Q11** Answer: 62 marks

First starts 0, 4, 8, 12, 16 minus arrivals 0–4.

Re-read: [Lesson 2.2.1](#l-2-2-1) — Round robin and the time quantum

**Q12** Answer: 182 marks

P2 runs 3–6 and 17–18.

Re-read: [Lesson 2.2.1](#l-2-2-1) — Round robin and the time quantum

**Q13** Answer: (D)1 mark

Many more switches.

- **(A) is wrong:** RR does not starve.
- **(B) is wrong:** That is FCFS's problem.
- **(C) is wrong:** Overhead lowers throughput.

Re-read: [Lesson 2.2.1](#l-2-2-1) — Round robin and the time quantum

**Q14** Answer: 22 marks

A 0–4, B 4–7; both now doing I/O, so the CPU is idle 7–9; B (back at 9) runs 9–12; A (back at 10) waits and runs 12–14.

Re-read: [Lesson 2.2.2](#l-2-2-2) — Multilevel queues, CPU and I/O bursts, CPU utilisation

**Q15** Answer: 0.191 mark

1 − 0.81.

Re-read: [Lesson 2.2.2](#l-2-2-2) — Multilevel queues, CPU and I/O bursts, CPU utilisation

Type next → [**3.1.1** Race conditions and the critical-section problem](#l-3-1-1)

# 🔒Phase 3 — Concurrency & Synchronization

## 📄Lesson 3.1.1 — Race conditions and the critical-section problem

Phase 3 › Concurrency & Synchronization › Chapter 3.1 The critical-section problem › Topic 3.1.1

Phase 3Ch 3.1 The critical-section problemTopic 3.1.1GATE weight: High≈ 45 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. Which parts of a process do its threads share? from [Lesson 1.2.1](#l-1-2-1)
2. Which IPC method needs the processes to synchronize by themselves? from [Lesson 1.2.2](#l-1-2-2)
3. Can the OS pre-empt a process in the middle of its work? from [Lesson 2.2.1](#l-2-2-1)

### 1The Hook

🎣

You and a friend share a bank account with ₹100. You both deposit ₹50 at the same moment from two ATMs. Each ATM reads ₹100, adds 50 and writes back ₹150. One deposit has vanished. Nothing was broken; two careful machines simply interleaved at the wrong moment. Threads that share variables have exactly this problem, and Phase 3 is about stopping it. GATE asks for "all possible final values" of such code almost every year.

### 2Predict First

🤔

A shared variable `count` is 0. Two threads each run `count++` once, at the same time. What can `count` be at the end?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

**1 or 2.** It is 2 if one thread finishes before the other starts. It is 1 if both read 0 before either writes back: one update is lost.

🗣️

In plain words

A line like `count++` looks like one step, but the CPU does it in three: read the value into a register, add 1, write it back. If another thread runs between those steps, it works with an out-of-date value and an update is lost. The fix is to let only **one thread at a time** run the code that touches the shared data.

#### 1. Why `count++` is not safe

`count++` becomes three machine instructions:

```
load  R, count      (R = count)
add   R, 1          (R = R + 1)
store count, R      (count = R)
```

Each thread has its **own** registers (Lesson 1.2.1), and a pre-emption can happen between any two instructions. One bad interleaving, with count = 0:

| Step | Thread 1 | Thread 2 | count |
| --- | --- | --- | --- |
| 1 | load R1 = 0 |  | 0 |
| 2 |  | load R2 = 0 | 0 |
| 3 | add: R1 = 1 |  | 0 |
| 4 |  | add: R2 = 1 | 0 |
| 5 | store count = 1 |  | 1 |
| 6 |  | store count = 1 | **1** |

Two increments, but count grew by only 1. This is a **lost update**.

#### 2. Race condition

A **race condition** happens when the result depends on the exact order (timing) in which threads run. Races are hard to find by testing, because the bad order may happen only rarely.

#### 3. The critical section

The **critical section (CS)** is the part of a program that uses shared data. Every process is organised like this:

```
entry section      (ask permission to enter)
   critical section
exit section       (announce that you left)
remainder section  (everything else)
```

The job of the entry and exit sections is to make sure the critical sections of different processes never overlap.

#### 4. The three requirements for a correct solution

1. **Mutual exclusion**: at most one process is inside its critical section at any time.
2. **Progress**: if the critical section is free and some processes want to enter, one of them must get in; the choice cannot be delayed forever, and a process that is busy in its remainder section has no say in it.
3. **Bounded waiting**: once a process asks to enter, there is a limit on how many times other processes may enter before it gets its turn (so no process waits forever).

Also, a solution must not assume anything about the speed of the processes or the number of CPUs.

#### 5. Finding all possible final values

Write each thread's statements as load / compute / store. Then:

- **One after the other** (no overlap) gives the "correct" value.
- **Both load before either stores**: whichever thread stores **last** wins, and the other update is lost.

Example: `c = 5`; thread 1 runs `c++`, thread 2 runs `c--`. Sequential → 5. Thread 1 stores last → 6. Thread 2 stores last → 4. Possible values **{4, 5, 6}**.

### 4Visual

```
Two threads, one shared variable, three steps each

Thread 1:  load ──── add ──── store
Thread 2:        load ──── add ──── store
                  ▲
                  both have read the same old value:
                  the store that happens last wins
```

### 5Worked Examples

Example 1 Easy

`x = 0`; two threads each run `x++` once. List the possible final values.

Solution

**1 or 2** (1 when both load 0 before either stores).

Example 2 Medium

`D = 100`. Thread 1 runs `D = D + 20`, thread 2 runs `D = D − 50`. Each statement is a load, a compute and a store. Possible final values?

Solution

One after the other: 70. Both load 100: if thread 1 stores last, **120**; if thread 2 stores last, **50**. So {50, 70, 120}.

Example 3 GATE

`x = 0`. Two threads each run `x++` twice (a loop of 2). What is the smallest possible final value?

Solution

**2.** Thread 1 loads 0. Thread 2 runs its first `x++` fully (x = 1). Thread 1 adds and stores 1 (thread 2's work is lost). Thread 2 loads 1 for its second `x++`. Thread 1 runs its second `x++` fully (x = 2). Thread 2 adds and stores 2. It can't end at 1: every store writes at least 1, so once a thread has stored, x never drops below 1. That thread's second load reads at least 1, so its second store writes at least 2, and the very last store of all is some thread's second store.

### 6GATE Traps

⚠️

- `x++`, `x = x + 1` and `x += 1` are **not** atomic (single-step) in general.
- The "lost update" needs both threads to **read before either writes**.
- Mutual exclusion alone is not enough: progress and bounded waiting matter too.
- Only shared variables matter; each thread's local variables and registers are private.

### 7Memory Hook

🧠

**"Read, change, write: anyone can sneak in between. Guard the critical section."**

### 8Connect the Dots

We know what a correct critical-section solution must do. The next lesson tries to build one using only ordinary variables, sees the simple attempts fail, and arrives at **Peterson's solution**.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**NAT1 markFinal values

`c = 5`; thread 1 runs `c++` and thread 2 runs `c--` at the same time. How many different final values of `c` are possible?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT1 markFinal values

`x = 0`; three threads each run `x++` once. Smallest possible final value of `x`?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT2 marksLoops

`x = 0`; two threads each run `x++` three times. Smallest possible final value of `x`?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**MCQ1 markRequirements

"A process that is running in its remainder section must not stop other processes from entering the critical section." This describes:

1. (A) atomicity
2. (B) bounded waiting
3. (C) progress
4. (D) mutual exclusion

**Q5**MSQ2 marksRequirements

Which of these must a correct critical-section solution guarantee?

1. (A) Mutual exclusion
2. (B) Every process runs at the same speed
3. (C) Progress
4. (D) Bounded waiting

### 10Rule Card

- `x++` = load, add, store; a pre-emption can fall between them.
- Race condition: the result depends on timing. Lost update: both load before either stores; the last store wins.
- Structure: entry section, CS, exit section, remainder section.
- Requirements: mutual exclusion, progress, bounded waiting; no assumptions about speed.
- `x++` in two loops of n ≥ 2 each from 0: minimum 2, maximum 2n.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

shared datarace conditionlost updatenon-atomic incrementcritical sectionentry, exit and remainder sectionsmutual exclusionprogressbounded waitingfinding all possible final values

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. Code, global data, heap and open files (each thread has its own stack, registers and PC).
2. Shared memory.
3. Yes: a timer interrupt can take the CPU away at any instruction.

#### Self-Test

**Q1** Answer: 31 mark

4, 5 or 6.

Re-read: [Lesson 3.1.1](#l-3-1-1) — Race conditions and the critical-section problem

**Q2** Answer: 11 mark

All three load 0 before any of them stores.

Re-read: [Lesson 3.1.1](#l-3-1-1) — Race conditions and the critical-section problem

**Q3** Answer: 22 marks

Thread 1 loads 0; thread 2 does two full increments (x = 2); thread 1 stores 1; thread 2 loads 1; thread 1 finishes its other two increments; thread 2 stores 2.

Re-read: [Lesson 3.1.1](#l-3-1-1) — Race conditions and the critical-section problem

**Q4** Answer: (C)1 mark

The decision involves only processes that want to enter.

- **(A) is wrong:** Not one of the three requirements.
- **(B) is wrong:** That limits how long a requester waits.
- **(D) is wrong:** That is about two processes inside at once.

Re-read: [Lesson 3.1.1](#l-3-1-1) — Race conditions and the critical-section problem

**Q5** Answer: (A) (C) (D)2 marks

The three requirements.

- **(B) is wrong:** A solution must not assume anything about speeds.

Re-read: [Lesson 3.1.1](#l-3-1-1) — Race conditions and the critical-section problem

Type next → [**3.1.2** Software solutions: turn and flag attempts, Peterson's algorithm](#l-3-1-2)

## 📄Lesson 3.1.2 — Software solutions: turn and flag attempts, Peterson's algorithm

Phase 3 › Concurrency & Synchronization › Chapter 3.1 The critical-section problem › Topic 3.1.2

Phase 3Ch 3.1 The critical-section problemTopic 3.1.2GATE weight: High≈ 50 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. Name the three requirements of a critical-section solution. from [Lesson 3.1.1](#l-3-1-1)
2. What does RR do when a process uses up its quantum? from [Lesson 2.2.1](#l-2-2-1)
3. What is a thread's private state? from [Lesson 1.2.1](#l-1-2-1)

### 1The Hook

🎣

Before special hardware instructions existed, people tried to solve the critical-section problem with ordinary variables. The first three ideas everyone has are all wrong, each in a different way, and GATE loves asking *which* requirement a given piece of code breaks. The fourth idea, **Peterson's solution**, gets everything right for two processes.

### 2Predict First

🤔

Lock-variable idea: `while (lock == 1) ; lock = 1; /* CS */ lock = 0;` Can two processes both get into the critical section?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

**Yes.** Both can see `lock == 0` before either sets it to 1. Checking and setting are two separate steps.

🗣️

In plain words

Two processes, P0 and P1, use shared variables to agree who may enter. "Waiting" here means looping on a condition until it becomes false (**busy waiting**). We check each attempt against the three requirements. Peterson's idea: say "I want to go", then politely offer the turn to the other one. If both want in, whoever offered last waits.

For process i, let j = 1 − i be the other process.

#### Attempt 1: a lock variable

```
while (lock == 1) ;   // wait
lock = 1;
/* critical section */
lock = 0;
```

**Fails mutual exclusion**: both can pass the `while` before either sets `lock = 1`.

#### Attempt 2: strict alternation (a `turn` variable)

```
while (turn != i) ;   // wait for my turn
/* critical section */
turn = j;             // give the turn away
```

- Mutual exclusion ✓ (turn is either 0 or 1).
- **Progress ✗**: the processes must take strict turns. If P0 goes off to do a long remainder section, P1 can enter once, then waits for P0 to take its turn, even though the CS is free.

#### Attempt 3: two flags

```
flag[i] = true;       // I want to enter
while (flag[j]) ;     // wait while the other wants to
/* critical section */
flag[i] = false;
```

- Mutual exclusion ✓.
- **Progress ✗**: if both set their flags before either checks, both wait for ever. Two processes each waiting for the other for ever is called a **deadlock**.

#### Peterson's solution (flags + turn)

```
flag[i] = true;                    // I want to enter
turn = j;                          // but you may go first
while (flag[j] && turn == j) ;     // wait only if you want it AND it is your turn
/* critical section */
flag[i] = false;                   // I am done
```

- **Mutual exclusion ✓**: if both want in, `turn` holds the value written **last**, so exactly one of them sees "it's the other's turn" and waits.
- **Progress ✓**: if the other doesn't want in, `flag[j]` is false and I enter at once.
- **Bounded waiting ✓**: after I leave, if I try again I set `turn = j`, so the waiting process gets in next (it waits at most one turn).
- Works for **two** processes; uses busy waiting. (On modern CPUs that reorder memory operations it needs extra "memory barrier" instructions.)

| Attempt | Mutual exclusion | Progress | What goes wrong |
| --- | --- | --- | --- |
| Lock variable | ✗ | ✓ | both pass the check before either sets the lock |
| Strict alternation | ✓ | ✗ | forced to take turns even when the other doesn't want to enter |
| Two flags | ✓ | ✗ | both raise flags, both wait for ever (deadlock) |
| Peterson | ✓ | ✓ | nothing (bounded waiting holds too) |

**Order matters.** If Peterson's first two lines are swapped (`turn = j;` before `flag[i] = true;`), mutual exclusion breaks: P0 sets turn = 1; P1 sets turn = 0, sets flag\[1\], sees flag\[0\] false and enters; P0 sets flag\[0\], sees turn == 0 (its own turn) and enters too.

### 4Visual

```
Peterson, both want in at the same time

P0: flag[0]=T   turn=1                 check: flag[1] && turn==1 ? -> turn is 0 -> ENTER
P1:       flag[1]=T   turn=0           check: flag[0] && turn==0 ? -> yes  -> WAIT
                           ^ written last, so P1 is the one that waits
```

### 5Worked Examples

Example 1 Easy

Strict alternation, turn = 0. P0 enters and leaves once (turn becomes 1), then spends an hour in its remainder section. P1 wants to enter twice. What happens?

Solution

P1 enters once (turn = 1), sets turn = 0 on leaving, then **waits for P0** even though no one is in the CS: progress is violated.

Example 2 Medium

Two-flag attempt: give an order of steps that makes both processes wait for ever.

Solution

P0 sets flag\[0\] = true; P1 sets flag\[1\] = true; now P0 loops on flag\[1\] and P1 loops on flag\[0\]: **deadlock**.

Example 3 GATE

In Peterson's solution a student replaces `while (flag[j] && turn == j)` by `while (flag[j] && turn == i)` but also writes `turn = i` instead of `turn = j`. Is mutual exclusion still guaranteed?

Solution

**Yes.** Now each process offers the turn to *itself* and waits while it is its own turn. Whoever wrote `turn` last still waits, so the logic is the same with the roles of the two values swapped. (Checked by trying every interleaving.)

### 6GATE Traps

⚠️

- Peterson's order is: **flag first, then turn**; swapping breaks mutual exclusion.
- Strict alternation satisfies mutual exclusion but **not progress**.
- The flags-only attempt can **deadlock**: a progress failure.
- Peterson's solution is for 2 processes and uses busy waiting (CPU time is wasted while spinning).

### 7Memory Hook

🧠

**"Raise your flag, give away the turn, wait only if the other wants it and it's theirs."**

### 8Connect the Dots

Software solutions are delicate and slow. The next lesson uses **special hardware instructions** that read and write a variable in one indivisible step, which makes locks simple.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**MCQ1 markStrict alternation

Strict alternation with a shared `turn` variable violates which requirement?

1. (A) Both mutual exclusion and progress
2. (B) Progress
3. (C) None of them
4. (D) Mutual exclusion

**Q2**MCQ1 markFlags

In the two-flag attempt (set your flag, then wait while the other's flag is set), what can go wrong?

1. (A) Both processes waiting for ever
2. (B) Nothing
3. (C) Both processes in the critical section together
4. (D) One process entering twice in a row

**Q3**MCQ1 markLock variable

The simple lock variable (`while (lock == 1); lock = 1;`) fails because:

1. (A) it can deadlock
2. (B) it violates mutual exclusion
3. (C) it needs special hardware
4. (D) it only works for 3 processes

**Q4**MSQ2 marksPeterson

Which statements about Peterson's solution (two processes) are true?

1. (A) It avoids busy waiting
2. (B) It guarantees progress
3. (C) It guarantees mutual exclusion
4. (D) It guarantees bounded waiting

**Q5**MCQ2 marksSwapped lines

Peterson's code for process i is changed to: `turn = j; flag[i] = true; while (flag[j] && turn == j);` What happens?

1. (A) Deadlock becomes possible
2. (B) It is still correct
3. (C) Bounded waiting is lost but mutual exclusion holds
4. (D) Mutual exclusion can be violated

### 10Rule Card

- Lock variable: fails mutual exclusion.
- Strict alternation (turn): mutual exclusion ✓, progress ✗.
- Two flags: mutual exclusion ✓, progress ✗ (deadlock).
- Peterson: flag\[i\] = true; turn = j; wait while (flag\[j\] && turn == j). All three ✓, 2 processes, busy waiting.
- Swapping Peterson's first two lines breaks mutual exclusion.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

busy waitinglock variable attemptstrict alternationtwo-flag attemptdeadlock (first meaning)Peterson's solutionwhy the order of Peterson's lines matters

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. Mutual exclusion, progress, bounded waiting.
2. Puts it at the back of the ready queue.
3. Its stack, registers and program counter.

#### Self-Test

**Q1** Answer: (B)1 mark

A process can be kept out of a free CS by a process in its remainder section.

- **(A) is wrong:** Mutual exclusion holds.
- **(C) is wrong:** Progress fails.
- **(D) is wrong:** Turn is 0 or 1, so only one enters.

Re-read: [Lesson 3.1.2](#l-3-1-2) — Software solutions: turn and flag attempts, Peterson's algorithm

**Q2** Answer: (A)1 mark

Both flags set, both wait.

- **(B) is wrong:** Deadlock is possible.
- **(C) is wrong:** Mutual exclusion holds.
- **(D) is wrong:** Entering twice in a row is allowed and harmless.

Re-read: [Lesson 3.1.2](#l-3-1-2) — Software solutions: turn and flag attempts, Peterson's algorithm

**Q3** Answer: (B)1 mark

Checking and setting are separate steps.

- **(A) is wrong:** Both can always proceed.
- **(C) is wrong:** It uses ordinary variables.
- **(D) is wrong:** Nonsense.

Re-read: [Lesson 3.1.2](#l-3-1-2) — Software solutions: turn and flag attempts, Peterson's algorithm

**Q4** Answer: (B) (C) (D)2 marks

All three requirements hold; the waiting is a busy loop.

- **(A) is wrong:** The `while` loop spins.

Re-read: [Lesson 3.1.2](#l-3-1-2) — Software solutions: turn and flag attempts, Peterson's algorithm

**Q5** Answer: (D)2 marks

P1 can enter between P0's two lines and P0 then sees its own turn.

- **(A) is wrong:** No interleaving blocks both.
- **(B) is wrong:** A bad interleaving exists.
- **(C) is wrong:** Mutual exclusion is the requirement that fails.

Re-read: [Lesson 3.1.2](#l-3-1-2) — Software solutions: turn and flag attempts, Peterson's algorithm

Type next → [**3.1.3** Hardware help: test-and-set, compare-and-swap, spinlocks](#l-3-1-3)

## 📄Lesson 3.1.3 — Hardware help: test-and-set, compare-and-swap, spinlocks

Phase 3 › Concurrency & Synchronization › Chapter 3.1 The critical-section problem › Topic 3.1.3

Phase 3Ch 3.1 The critical-section problemTopic 3.1.3GATE weight: Medium≈ 40 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. Peterson's solution sets which variable first? from [Lesson 3.1.2](#l-3-1-2)
2. Which requirement does strict alternation break? from [Lesson 3.1.2](#l-3-1-2)
3. Can user programs disable interrupts? from [Lesson 0.1.2](#l-0-1-2)

### 1The Hook

🎣

The lock-variable attempt failed only because "check" and "set" were two separate steps. What if the hardware could do both **in one indivisible step**? Every modern CPU has such instructions (test-and-set, compare-and-swap), and every real lock is built on them. GATE asks what these locks guarantee and where they fail.

### 2Predict First

🤔

On a computer with one CPU, the kernel disables interrupts, updates a shared counter, then enables interrupts. Can anything interrupt the update?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

**No.** With interrupts off there is no timer interrupt and so no pre-emption. (On several CPUs this does not work: other CPUs keep running.)

🗣️

In plain words

An **atomic** instruction finishes completely before anything else can touch the same memory. Test-and-set reads the old value of a lock and sets it to "taken" in one go. If the old value was "free", you got the lock; otherwise try again. A lock where the waiter keeps trying in a loop is a **spinlock**.

#### 1. Disabling interrupts

Works on a single CPU for short kernel code. Not usable by user programs (privileged), and useless on multiprocessors (other CPUs still run).

#### 2. Test-and-set (TSL)

```
bool TestAndSet(bool *target) {   // executed atomically by the hardware
    bool old = *target;
    *target = true;
    return old;
}

while (TestAndSet(&lock)) ;   // spin until the old value was false
/* critical section */
lock = false;
```

- Mutual exclusion ✓ (only one caller can see `false`).
- Progress ✓.
- **Bounded waiting ✗**: an unlucky process can lose the race every single time. (A version with a `waiting[]` array that hands the lock to the next waiter in circular order fixes this.)

#### 3. Swap and compare-and-swap (CAS)

- **Swap(a, b)** exchanges two variables atomically: `key = true; while (key) Swap(&lock, &key);`
- **CAS(&v, expected, new)**: if `v == expected`, set `v = new`; always **return the old value**. Lock: `while (CAS(&lock, 0, 1) != 0) ;` and unlock with `lock = 0`.

#### 4. Spinlocks: when are they good?

- Waiting costs CPU time (busy waiting) but needs **no context switch**.
- Good: multiprocessors and **very short** critical sections.
- Bad: one CPU (the lock holder can't run while you spin), or long critical sections.

#### 5. Priority inversion

With strict priority scheduling: a low-priority process L holds a spinlock; a high-priority process H arrives and spins on it. H always gets the CPU, so L never runs to release the lock, and H spins for ever. Fix: **priority inheritance** (L temporarily gets H's priority until it releases the lock).

### 4Visual

```
Three processes racing for a TSL lock (lock = false at first)

P1: TSL -> returns false, lock = true  -> ENTERS
P2: TSL -> returns true                -> spins
P3: TSL -> returns true                -> spins
P1: lock = false
P3: TSL -> returns false, lock = true  -> ENTERS   (P2 may lose again and again)
```

### 5Worked Examples

Example 1 Easy

x = 5. A thread runs `CAS(&x, 5, 9)`. What is returned, and what is x afterwards?

Solution

Returns the old value **5**; since it matched, x becomes **9**.

Example 2 Medium

x = 7. A thread runs `CAS(&x, 5, 9)`. Returned value and new x?

Solution

Returns **7**; 7 ≠ 5, so x **stays 7**.

Example 3 GATE

Why is a TSL spinlock a poor choice on a single-CPU system for a long critical section?

Solution

While the waiting process spins, the lock holder is not running (one CPU), so the spinning only wastes the waiter's time slice until the holder is scheduled again and finishes.

### 6GATE Traps

⚠️

- A TSL lock gives mutual exclusion and progress, but **not** bounded waiting.
- CAS returns the **old** value, whether or not it changed anything.
- Disabling interrupts: one CPU only, kernel mode only.
- Priority inversion: high priority spins, low priority holds the lock and never runs.

### 7Memory Hook

🧠

**"Check and set in one hardware step: that is all a lock needs."**

### 8Connect the Dots

Chapter 3.1 is complete: we can build locks, but they all spin. Chapter 3.2 introduces the **semaphore**, a tool that lets a waiting process sleep instead of spinning, and can also count resources and order events.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**MCQ1 markTSL

A lock built as `while (TestAndSet(&lock)) ;` guarantees:

1. (A) none of the requirements
2. (B) mutual exclusion only
3. (C) mutual exclusion and progress, but not bounded waiting
4. (D) all three requirements

**Q2**NAT1 markCAS

x = 12. A thread executes `CAS(&x, 12, 20)`. What value does the call return?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT1 markCAS

x = 4. A thread executes `CAS(&x, 3, 8)`. What is x afterwards?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**MCQ1 markInterrupts

Disabling interrupts to protect a critical section does not work on:

1. (A) a single-CPU system in kernel mode
2. (B) a multiprocessor system
3. (C) the OS kernel
4. (D) very short critical sections

**Q5**MCQ2 marksPriority inversion

Strict priority scheduling, one CPU. Low-priority L holds a spinlock; high-priority H starts spinning on the same lock. What happens?

1. (A) L finishes quickly because H waits
2. (B) H and L share the CPU equally
3. (C) The lock is released automatically
4. (D) H spins for ever because L never gets the CPU

### 10Rule Card

- Atomic instruction: finishes before anything else touches that memory.
- TSL: return old, set true; lock = spin until old is false. ME ✓, progress ✓, bounded waiting ✗.
- CAS(&v, e, n): if v == e then v = n; returns the old value. Swap exchanges atomically.
- Spinlocks: good on multiprocessors for short sections; no context switch.
- Disabling interrupts: one CPU, kernel only. Priority inversion → priority inheritance.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

atomic instructiondisabling interruptstest-and-setswapcompare-and-swapspinlockwhen to spinbounded-waiting TSLpriority inversionpriority inheritance

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. flag\[i\] (then turn).
2. Progress.
3. No: it is a privileged instruction.

#### Self-Test

**Q1** Answer: (C)1 mark

A process can lose the race indefinitely.

- **(A) is wrong:** Mutual exclusion holds.
- **(B) is wrong:** Progress also holds.
- **(D) is wrong:** Bounded waiting fails.

Re-read: [Lesson 3.1.3](#l-3-1-3) — Hardware help: test-and-set, compare-and-swap, spinlocks

**Q2** Answer: 121 mark

CAS returns the old value.

Re-read: [Lesson 3.1.3](#l-3-1-3) — Hardware help: test-and-set, compare-and-swap, spinlocks

**Q3** Answer: 41 mark

4 ≠ 3, so x is unchanged.

Re-read: [Lesson 3.1.3](#l-3-1-3) — Hardware help: test-and-set, compare-and-swap, spinlocks

**Q4** Answer: (B)1 mark

Other CPUs keep running.

- **(A) is wrong:** There it does work.
- **(C) is wrong:** The kernel can use it on one CPU.
- **(D) is wrong:** Short sections are exactly where it works.

Re-read: [Lesson 3.1.3](#l-3-1-3) — Hardware help: test-and-set, compare-and-swap, spinlocks

**Q5** Answer: (D)2 marks

H always wins the CPU but needs L to run.

- **(A) is wrong:** L can't run while H is ready.
- **(B) is wrong:** Strict priority doesn't share.
- **(C) is wrong:** Locks are not released automatically.

Re-read: [Lesson 3.1.3](#l-3-1-3) — Hardware help: test-and-set, compare-and-swap, spinlocks

Type next → [**LI-3.1** Chapter 3.1 Lock-in](#l-LI-3-1)

## 🔒Chapter 3.1 Lock-in — The critical-section problem

Phase 3 › Concurrency & Synchronization › Chapter 3.1 The critical-section problem

Phase 3Ch 3.1 The critical-section problem

### ACompressed recap

🧾

`x++` = load, add, store; a race loses updates (last store wins). Critical section with entry/exit; requirements: mutual exclusion, progress, bounded waiting. Lock variable ✗ME; strict alternation ✗progress; two flags ✗progress (deadlock); Peterson ✓✓✓ for 2 processes (flag first, then turn). TSL/CAS: atomic; TSL lock has no bounded waiting; CAS returns the old value; spinlocks suit short sections on multiprocessors; priority inversion.

### BMerged rule card

[3.1.1](#l-3-1-1) Race conditions and the critical-section problem

- `x++` = load, add, store; a pre-emption can fall between them.
- Race condition: the result depends on timing. Lost update: both load before either stores; the last store wins.
- Structure: entry section, CS, exit section, remainder section.
- Requirements: mutual exclusion, progress, bounded waiting; no assumptions about speed.
- `x++` in two loops of n ≥ 2 each from 0: minimum 2, maximum 2n.

[3.1.2](#l-3-1-2) Software solutions: turn and flag attempts, Peterson's algorithm

- Lock variable: fails mutual exclusion.
- Strict alternation (turn): mutual exclusion ✓, progress ✗.
- Two flags: mutual exclusion ✓, progress ✗ (deadlock).
- Peterson: flag\[i\] = true; turn = j; wait while (flag\[j\] && turn == j). All three ✓, 2 processes, busy waiting.
- Swapping Peterson's first two lines breaks mutual exclusion.

[3.1.3](#l-3-1-3) Hardware help: test-and-set, compare-and-swap, spinlocks

- Atomic instruction: finishes before anything else touches that memory.
- TSL: return old, set true; lock = spin until old is false. ME ✓, progress ✓, bounded waiting ✗.
- CAS(&v, e, n): if v == e then v = n; returns the old value. Swap exchanges atomically.
- Spinlocks: good on multiprocessors for short sections; no context switch.
- Disabling interrupts: one CPU, kernel only. Priority inversion → priority inheritance.

### CInterleaved GATE-style questions

**Q1**NAT1 markFinal values

`D = 100`. Thread 1 runs `D = D + 20`, thread 2 runs `D = D − 50`, each as load/compute/store. Largest possible final value of D?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT2 marksFinal values

`x = 0`. Two threads each run `x++` twice. How many different final values of x are possible?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**MCQ1 markRequirements

"After a process requests entry, other processes can enter only a limited number of times before it does." This is:

1. (A) bounded waiting
2. (B) deadlock freedom
3. (C) mutual exclusion
4. (D) progress

**Q4**MCQ1 markTwo flags

The two-flag attempt (raise your flag, wait while the other's flag is up) satisfies mutual exclusion. Which requirement fails?

1. (A) Mutual exclusion
2. (B) Both
3. (C) Progress
4. (D) Neither

**Q5**MCQ2 marksPeterson

In Peterson's solution, both processes want to enter, and P1 was the last to write `turn`. Who enters first?

1. (A) P1
2. (B) P0
3. (C) Neither: deadlock
4. (D) Both

**Q6**MCQ1 markTSL

Which requirement does the simple test-and-set spinlock NOT guarantee?

1. (A) Mutual exclusion
2. (B) It guarantees all three
3. (C) Bounded waiting
4. (D) Progress

**Q7**NAT1 markCAS

`lock = 0`. Two threads call `CAS(&lock, 0, 1)` one after the other. What does the second call return?

Numerical answer: \_\_\_\_\_\_\_\_

**Q8**MSQ2 marksSpinlocks

Which are true about spinlocks?

1. (A) A waiting process uses CPU time
2. (B) They suit very short critical sections on multiprocessors
3. (C) They are ideal for long critical sections on a single CPU
4. (D) They avoid context-switch overhead

### DAnswer Vault

🔐 Open the Answer Vault

**Q1** Answer: 1201 mark

Both load 100; thread 1 stores last.

Re-read: [Lesson 3.1.1](#l-3-1-1) — Race conditions and the critical-section problem

**Q2** Answer: 32 marks

2, 3 or 4.

Re-read: [Lesson 3.1.1](#l-3-1-1) — Race conditions and the critical-section problem

**Q3** Answer: (A)1 mark

A limit on the wait.

- **(B) is wrong:** Not one of the three names.
- **(C) is wrong:** About two inside at once.
- **(D) is wrong:** About not postponing the decision.

Re-read: [Lesson 3.1.1](#l-3-1-1) — Race conditions and the critical-section problem

**Q4** Answer: (C)1 mark

Both raise flags and wait for ever.

- **(A) is wrong:** Mutual exclusion holds.
- **(B) is wrong:** Only progress.
- **(D) is wrong:** Progress fails.

Re-read: [Lesson 3.1.2](#l-3-1-2) — Software solutions: turn and flag attempts, Peterson's algorithm

**Q5** Answer: (B)2 marks

P1 set turn = 0, giving the turn to P0.

- **(A) is wrong:** P1 gave the turn away.
- **(C) is wrong:** Peterson never deadlocks.
- **(D) is wrong:** Mutual exclusion holds.

Re-read: [Lesson 3.1.2](#l-3-1-2) — Software solutions: turn and flag attempts, Peterson's algorithm

**Q6** Answer: (C)1 mark

A process can keep losing.

- **(A) is wrong:** Holds.
- **(B) is wrong:** Bounded waiting fails.
- **(D) is wrong:** Holds.

Re-read: [Lesson 3.1.3](#l-3-1-3) — Hardware help: test-and-set, compare-and-swap, spinlocks

**Q7** Answer: 11 mark

The first call changed lock to 1.

Re-read: [Lesson 3.1.3](#l-3-1-3) — Hardware help: test-and-set, compare-and-swap, spinlocks

**Q8** Answer: (A) (B) (D)2 marks

Busy waiting with no switch.

- **(C) is wrong:** On one CPU the holder can't run while you spin.

Re-read: [Lesson 3.1.3](#l-3-1-3) — Hardware help: test-and-set, compare-and-swap, spinlocks

Type next → [**3.2.1** Semaphores: wait, signal, counting and binary semaphores](#l-3-2-1)

## 📄Lesson 3.2.1 — Semaphores: wait, signal, counting and binary semaphores

Phase 3 › Concurrency & Synchronization › Chapter 3.2 Semaphores and classic problems › Topic 3.2.1

Phase 3Ch 3.2 Semaphores and classic problemsTopic 3.2.1GATE weight: High≈ 50 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. What does a TSL lock fail to guarantee? from [Lesson 3.1.3](#l-3-1-3)
2. What is busy waiting? from [Lesson 3.1.2](#l-3-1-2)
3. Which state does a process enter while waiting for an event? from [Lesson 1.1.1](#l-1-1-1)

### 1The Hook

🎣

A library has 3 copies of a popular book. A counter on the desk shows how many are left: borrowing subtracts 1, returning adds 1, and if it shows 0 you wait in a queue. That counter is a **semaphore**, invented by Dijkstra. It can act as a lock (1 copy), count resources (k copies), or make one thing happen before another (0 copies at the start). GATE asks both semaphore arithmetic and "which outputs are possible" puzzles.

### 2Predict First

🤔

A semaphore starts at 3. Five processes each call wait on it, and none of them signals. How many get through and how many wait?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

**3 get through**, 2 wait (block).

🗣️

In plain words

A semaphore is a shared integer you may touch only with two operations. **wait** (also called P or down): take one unit; if none is left, sleep until one is available. **signal** (V or up): give one unit back and wake a sleeper if there is one. Both operations are atomic.

#### 1. Definition

Simple (busy-waiting) version:

```
wait(S)   { while (S <= 0) ;  S--; }
signal(S) { S++; }
```

**Blocking** version (no spinning; each semaphore keeps a queue of sleeping processes):

```
wait(S)   { S--;  if (S < 0)  { add this process to S's queue; block(); } }
signal(S) { S++;  if (S <= 0) { remove a process from S's queue; wake it up; } }
```

In the blocking version a **negative value −k means k processes are waiting**.

#### 2. Two kinds

- **Binary semaphore** (value 0 or 1): a lock, often called a **mutex**.
- **Counting semaphore** (any value): k identical resources.

#### 3. Three uses

| Use | Initial value | Pattern |
| --- | --- | --- |
| Mutual exclusion | 1 | `wait(m); CS; signal(m);` in every process |
| At most k at a time | k | same pattern; up to k inside |
| Ordering ("A before B") | 0 | P1: `A; signal(s);` P2: `wait(s); B;` |

#### 4. Semaphore arithmetic

For the blocking definition: **final value = initial − (number of waits) + (number of signals)**. Initial 10, then 6 waits and 4 signals → 10 − 6 + 4 = **8**.

#### 5. Mistakes with semaphores

- Two processes taking two semaphores in opposite orders can block each other for ever: P1 `wait(S); wait(Q);` and P2 `wait(Q); wait(S);` → each holds one and waits for the other (deadlock).
- Forgetting `signal` (the lock is never released), or using `signal` before `wait` by mistake.
- If the queue is LIFO, some process may wait for ever (**starvation**).

#### 6. "Which outputs are possible?" puzzles

Simulate: keep the semaphore values, and at each moment only allow a process to pass `wait(s)` if s > 0. Example (s = 0, t = 1):

```
P1: print "A"; signal(s); wait(t); print "C";
P2: wait(s); print "B"; signal(t);
```

A must come first (P2 is blocked on s = 0). Then P1 can pass `wait(t)` at once (t = 1), so C can come before or after B: **ABC or ACB**.

### 4Visual

```
Counting semaphore S = 3, five processes call wait

call:     wait  wait  wait  wait  wait
S after:   2     1     0    -1    -2
result:   go    go    go   sleep sleep     (-2 = two sleepers)

signal(S): S = -1, one sleeper wakes and goes
```

### 5Worked Examples

Example 1 Easy

A counting semaphore starts at 10; then 6 wait and 4 signal operations are done. Final value?

Solution

10 − 6 + 4 = **8**.

Example 2 Medium

We want statement B in process P2 to run only after statement A in process P1. Write the code.

Solution

Semaphore s = **0**. P1: `A; signal(s);` P2: `wait(s); B;`

Example 3 GATE

A counting semaphore is initialised to 7. Then 20 wait and 15 signal operations are performed. What is its final value?

Solution

7 − 20 + 15 = **2**.

### 6GATE Traps

⚠️

- The final-value formula uses the blocking definition (values may go negative).
- Mutex starts at **1**; an ordering semaphore starts at **0**.
- Every process using the shared data must use the semaphore; one process skipping it brings the race back.
- wait/signal themselves must be atomic (the OS implements them with a short lock).

### 7Memory Hook

🧠

**"wait takes one or sleeps; signal gives one and wakes; −k = k sleepers."**

### 8Connect the Dots

With semaphores we can now solve the famous synchronization puzzles: a **bounded buffer**, **readers and writers**, and the **dining philosophers**.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**NAT1 markArithmetic

A semaphore is initialised to 10. Then 6 wait and 4 signal operations complete. Final value?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT1 markNegative value

In the blocking implementation, a semaphore's value is −3. How many processes are waiting on it?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**MCQ1 markOrdering

To make statement B (in P2) run only after statement A (in P1), the semaphore used should start at:

1. (A) 0
2. (B) the number of processes
3. (C) 1
4. (D) −1

**Q4**NAT1 markCounting

A counting semaphore starts at 3 and every process runs `wait(S); CS; signal(S);`. At most how many processes can be inside CS at the same time?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**NAT2 marksOutputs

s = 0, t = 1. P1: `print "A"; signal(s); wait(t); print "C";` P2: `wait(s); print "B"; signal(t);` How many different output strings are possible?

Numerical answer: \_\_\_\_\_\_\_\_

### 10Rule Card

- wait/P: S--; if S \< 0 block. signal/V: S++; if S ≤ 0 wake one. Atomic.
- Negative value −k = k processes waiting. Final value = initial − waits + signals.
- Binary (mutex, starts 1) vs counting (starts k). Ordering semaphore starts 0.
- Opposite orders of waits can deadlock; LIFO queues can starve.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

semaphorewait (P) and signal (V)busy-waiting and blocking implementationsnegative value meaningbinary semaphore (mutex)counting semaphoreordering with a semaphoresemaphore arithmeticpossible-output puzzles

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. Bounded waiting.
2. Looping on a condition while using the CPU.
3. Waiting (blocked).

#### Self-Test

**Q1** Answer: 81 mark

10 − 6 + 4.

Re-read: [Lesson 3.2.1](#l-3-2-1) — Semaphores: wait, signal, counting and binary semaphores

**Q2** Answer: 31 mark

−k means k waiters.

Re-read: [Lesson 3.2.1](#l-3-2-1) — Semaphores: wait, signal, counting and binary semaphores

**Q3** Answer: (A)1 mark

P2 must block until P1 signals.

- **(B) is wrong:** Same problem.
- **(C) is wrong:** P2 could run B immediately.
- **(D) is wrong:** Semaphores start at 0 or more.

Re-read: [Lesson 3.2.1](#l-3-2-1) — Semaphores: wait, signal, counting and binary semaphores

**Q4** Answer: 31 mark

Three units.

Re-read: [Lesson 3.2.1](#l-3-2-1) — Semaphores: wait, signal, counting and binary semaphores

**Q5** Answer: 22 marks

ABC and ACB.

Re-read: [Lesson 3.2.1](#l-3-2-1) — Semaphores: wait, signal, counting and binary semaphores

Type next → [**3.2.2** Classic problems: bounded buffer, readers–writers, dining philosophers](#l-3-2-2)

## 📄Lesson 3.2.2 — Classic problems: bounded buffer, readers–writers, dining philosophers

Phase 3 › Concurrency & Synchronization › Chapter 3.2 Semaphores and classic problems › Topic 3.2.2

Phase 3Ch 3.2 Semaphores and classic problemsTopic 3.2.2GATE weight: High≈ 50 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. A semaphore for ordering starts at? from [Lesson 3.2.1](#l-3-2-1)
2. Final value of a semaphore? from [Lesson 3.2.1](#l-3-2-1)
3. In producer–consumer, when must the producer wait? from [Lesson 1.2.2](#l-1-2-2)

### 1The Hook

🎣

Three stories appear again and again in GATE: a **bakery shelf** with limited space (bounded buffer), a **notice board** that many can read but only one can edit (readers–writers), and **five philosophers** with five chopsticks (dining philosophers). Each one shows a different danger, and the exam usually asks what goes wrong when one line is moved.

### 2Predict First

🤔

In the bounded-buffer solution, the consumer does `wait(full); wait(mutex);`. What if it did `wait(mutex); wait(full);` instead and the buffer is empty?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

It takes the mutex, then sleeps on `full` **while holding the mutex**. The producer can never get the mutex to add an item: **deadlock**.

🗣️

In plain words

Each classic problem is a pattern to copy. Bounded buffer: count the empty and full slots with two counting semaphores and guard the buffer with a mutex. Readers–writers: the first reader locks out writers and the last reader lets them back in. Dining philosophers: if everyone grabs the left chopstick first, everyone can end up stuck.

#### 1. Bounded buffer (producer–consumer with N slots)

Semaphores: `mutex = 1`, `empty = N` (free slots), `full = 0` (filled slots).

```
Producer:                    Consumer:
  wait(empty);                 wait(full);
  wait(mutex);                 wait(mutex);
  add item to buffer;          remove item from buffer;
  signal(mutex);               signal(mutex);
  signal(full);                signal(empty);
```

- Always do the **counting wait first, then the mutex**. Swapping the two waits in the consumer deadlocks on an empty buffer; swapping them in the producer deadlocks on a full buffer.
- Swapping the two **signals** is harmless.

#### 2. Readers–writers (first version: readers have priority)

Many readers may read together; a writer needs the data alone. Semaphores: `rw = 1` (writers' lock), `mutex = 1` (protects `read_count`), and `read_count = 0`.

```
Writer:                      Reader:
  wait(rw);                    wait(mutex);
  write;                       read_count++;
  signal(rw);                  if (read_count == 1) wait(rw);   // first reader locks writers out
                               signal(mutex);
                               read;
                               wait(mutex);
                               read_count--;
                               if (read_count == 0) signal(rw); // last reader lets writers in
                               signal(mutex);
```

- Readers overlap; a writer is always alone.
- **Writers can starve**: while readers keep arriving, `read_count` never reaches 0. (A second version gives writers priority and can starve readers.)

#### 3. Dining philosophers

Five philosophers sit at a round table with one chopstick between each pair (chopstick semaphores all 1). To eat, a philosopher needs both neighbouring chopsticks.

```
wait(chop[i]);  wait(chop[(i+1) % 5]);   // left, then right
eat;
signal(chop[(i+1) % 5]);  signal(chop[i]);
```

If all five pick up their left chopstick at once, each waits for ever for the right one: **deadlock**. Fixes:

- Allow at most **4** at the table at a time (a counting semaphore `room = 4`).
- **Asymmetry**: one philosopher (or every odd one) picks the right chopstick first.
- Pick up **both** chopsticks only when both are free (inside a critical section).

At most ⌊5/2⌋ = **2** philosophers can eat at the same time.

### 4Visual

Five philosophers, five chopsticks. Philosopher i needs c(i) on one side and c(i+1) on the other; if all take one side first, all wait.

### 5Worked Examples

Example 1 Easy

A bounded buffer has 8 slots. Initial values of `empty`, `full` and `mutex`?

Solution

empty = **8**, full = **0**, mutex = **1**.

Example 2 Medium

In the readers–writers solution, why does only the *first* reader do `wait(rw)`?

Solution

Once one reader holds `rw`, writers are already locked out; later readers just add to `read_count`. The **last** reader releases `rw`.

Example 3 GATE

The producer is written as `wait(mutex); wait(empty); add; signal(mutex); signal(full);` (the consumer is correct). When can this deadlock?

Solution

When the buffer is **full**: the producer takes the mutex and sleeps on `empty`; the consumer can't get the mutex to remove an item.

### 6GATE Traps

⚠️

- Order of **waits** matters (counting first, mutex second); order of signals does not.
- First readers–writers: readers can lock writers out for ever (writer starvation), not the other way round.
- Dining philosophers deadlock needs **all** philosophers to grab the same side first.
- "At most 4 at the table" works because then at least one philosopher can get both chopsticks.

### 7Memory Hook

🧠

**"Count first, lock second. First reader locks, last reader unlocks. Break the circle of philosophers."**

### 8Connect the Dots

Semaphores are powerful but easy to misuse: one swapped line causes deadlock. The next lesson introduces **monitors**, which let the compiler handle the locking, and collects a step-by-step method for GATE's "analyse this concurrent code" questions.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**MCQ1 markBounded buffer

In the consumer, `wait(full); wait(mutex);` is changed to `wait(mutex); wait(full);`. What can happen?

1. (A) Two consumers remove the same item
2. (B) Nothing changes
3. (C) Deadlock when the buffer is full
4. (D) Deadlock when the buffer is empty

**Q2**NAT1 markInitial values

A bounded buffer has 12 slots. Initial value of the semaphore `empty`?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**MCQ1 markReaders–writers

In the first (reader-priority) readers–writers solution, who can starve?

1. (A) Readers
2. (B) Writers
3. (C) Neither
4. (D) Both equally

**Q4**NAT1 markPhilosophers

Five dining philosophers: what is the maximum number that can eat at the same time?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**MSQ2 marksPhilosophers

Which changes prevent deadlock in the dining philosophers (each normally picks left, then right)?

1. (A) A philosopher picks up both chopsticks only when both are free
2. (B) Allow at most 4 philosophers at the table
3. (C) One philosopher picks right first, then left
4. (D) Every philosopher picks right first, then left

### 10Rule Card

- Bounded buffer: mutex = 1, empty = N, full = 0; counting wait before mutex wait; signals in any order.
- Readers–writers (reader priority): first reader waits on rw, last reader signals rw; writers may starve.
- Dining philosophers: all left-first → deadlock; fixes: ≤ 4 at table, asymmetry, both-at-once. Max ⌊n/2⌋ eat together.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

bounded-buffer problemempty/full/mutex semaphoresorder of waitsreaders–writers problemread_countwriter starvationdining philosophersdeadlock fixes for the philosophers

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. 0.
2. Initial − waits + signals.
3. When the buffer is full.

#### Self-Test

**Q1** Answer: (D)1 mark

The consumer sleeps on full while holding mutex.

- **(A) is wrong:** The mutex still protects the buffer.
- **(B) is wrong:** A deadlock appears.
- **(C) is wrong:** That is the producer's case.

Re-read: [Lesson 3.2.2](#l-3-2-2) — Classic problems: bounded buffer, readers–writers, dining philosophers

**Q2** Answer: 121 mark

All slots are free.

Re-read: [Lesson 3.2.2](#l-3-2-2) — Classic problems: bounded buffer, readers–writers, dining philosophers

**Q3** Answer: (B)1 mark

A steady stream of readers keeps read_count above 0.

- **(A) is wrong:** Readers are favoured.
- **(C) is wrong:** Writers can.
- **(D) is wrong:** Only writers here.

Re-read: [Lesson 3.2.2](#l-3-2-2) — Classic problems: bounded buffer, readers–writers, dining philosophers

**Q4** Answer: 21 mark

Each eater needs two of the five chopsticks.

Re-read: [Lesson 3.2.2](#l-3-2-2) — Classic problems: bounded buffer, readers–writers, dining philosophers

**Q5** Answer: (A) (B) (C)2 marks

Each breaks the circular wait.

- **(D) is wrong:** All-right-first is the same circle in the other direction.

Re-read: [Lesson 3.2.2](#l-3-2-2) — Classic problems: bounded buffer, readers–writers, dining philosophers

Type next → [**3.2.3** Monitors, and reasoning about concurrent code](#l-3-2-3)

## 📄Lesson 3.2.3 — Monitors, and reasoning about concurrent code

Phase 3 › Concurrency & Synchronization › Chapter 3.2 Semaphores and classic problems › Topic 3.2.3

Phase 3Ch 3.2 Semaphores and classic problemsTopic 3.2.3GATE weight: Medium≈ 45 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. Initial value of `full` in a bounded buffer? from [Lesson 3.2.2](#l-3-2-2)
2. How many processes can be inside a CS guarded by a semaphore that starts at 1? from [Lesson 3.2.1](#l-3-2-1)
3. Does Peterson's solution guarantee bounded waiting? from [Lesson 3.1.2](#l-3-1-2)

### 1The Hook

🎣

Semaphores are like raw wires: powerful, but one wire in the wrong place causes a fire. A **monitor** is like a switchboard: the dangerous wiring is done for you. After monitors, this lesson gives a **five-step method** for the GATE questions that show a few lines of concurrent code and ask what can happen.

### 2Predict First

🤔

A semaphore is signalled when nobody is waiting; later a process waits on it. Does the later wait block? Now the same with a monitor's condition variable: `x.signal()` with nobody waiting, then `x.wait()`. Does that wait block?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

Semaphore: **no**, the earlier signal was remembered (value went up). Condition variable: **yes**, a signal with no waiter is simply **lost**.

🗣️

In plain words

A monitor is a box containing shared data and the only functions allowed to touch it. The language makes sure only **one** process is running inside the box at a time, so you can't forget the lock. If a process inside must wait for something, it waits on a **condition variable**, which also lets others into the box meanwhile.

#### 1. Monitors

```
monitor Account {
    int balance;
    condition enough;
    void withdraw(int a) { while (balance < a) enough.wait(); balance -= a; }
    void deposit(int a)  { balance += a; enough.signal(); }
}
```

- At most **one process active** inside the monitor at a time (mutual exclusion is automatic).
- `x.wait()`: the caller sleeps on x **and releases the monitor**.
- `x.signal()`: wakes **one** process sleeping on x; if none is sleeping, **nothing happens** (unlike a semaphore's signal, which is remembered).
- After a signal, who runs first? **Signal-and-wait**: the woken process runs at once. **Signal-and-continue**: the signaller continues; the woken one runs later, so it must re-check its condition (that is why the example uses `while`, not `if`).

#### 2. A five-step method for "analyse this code" questions

1. **Mark shared vs local** variables (locals and registers are private to each thread).
2. **Split statements** into load / compute / store if the question says statements are not atomic; otherwise treat each line as one step.
3. **Try the extremes**: run the threads one after the other, and try "everyone reads before anyone writes".
4. **Track semaphore values**: a `wait` can pass only when the value is above 0; a counting semaphore of k lets k threads overlap.
5. **Ask four questions**: Is mutual exclusion kept? Can all threads block for ever (deadlock)? Can a free CS be refused (progress)? Can one thread wait for ever (starvation)?

#### 3. Worked GATE-style example

`x = 0`. Processes W and X each do `x = x + 1`; Y and Z each do `x = x − 2`. Each process does `wait(S)` before reading x and `signal(S)` after storing it, and **S starts at 2**. What is the largest possible final x?

- S = 2 lets **two** processes be between wait and signal together, so two can still race.
- To make x large, lose the decrements. W and Y enter; both read 0; Y stores −2 and leaves; W stores **1** (Y's −2 is lost) and leaves.
- X and Z enter; both read 1; Z stores −1 and leaves; X stores **2** (Z's −2 is lost).
- Largest value **2**. Losing the increments instead gives the smallest value, **−4**.

### 4Visual

A process that calls x.wait() sleeps in x's queue and lets the next process into the monitor.

### 5Worked Examples

Example 1 Easy

In a monitor, process A calls `x.signal()` and no process is waiting on x. Later B calls `x.wait()`. Does B sleep?

Solution

**Yes.** A's signal had no effect, so nothing is remembered.

Example 2 Medium

`B = 3`. P1 runs `C = B − 1; B = 2 * C;` and P2 runs `D = 2 * B; B = D − 1;`. Each line is atomic; C and D are local. How many different final values can B have?

Solution

P1 then P2: B = 4, then 7. P2 then P1: B = 5, then 8. Interleaved: C = 2, D = 6, then the two stores of B in either order give **5** or **4**. Values {4, 5, 7, 8} → **4** different values.

Example 3 GATE

In the W, X, Y, Z example above, what if S starts at 1?

Solution

Then only one process at a time touches x, so there is no race: x = 0 + 1 + 1 − 2 − 2 = **−2**, always.

### 6GATE Traps

⚠️

- A condition variable's signal is **lost** if no one waits; a semaphore's signal is remembered.
- `x.wait()` releases the monitor while sleeping.
- A counting semaphore larger than 1 used as a "lock" lets several processes in, so races are still possible.
- Read carefully whether each line is atomic or must be split into load/compute/store.

### 7Memory Hook

🧠

**"Monitor: one inside, wait releases, signal can be lost. For code questions: shared, split, extremes, semaphores, four questions."**

### 8Connect the Dots

Phase 3 is complete. We met deadlock several times (flags, semaphores in the wrong order, philosophers). Phase 4 studies **deadlock** itself: exactly when it can happen and how an OS prevents, avoids, detects or recovers from it.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**MCQ1 markCondition variables

In a monitor, `x.signal()` is called when no process is waiting on x. What happens?

1. (A) Nothing happens
2. (B) The caller blocks
3. (C) The signal is saved for the next `x.wait()`
4. (D) An error is raised

**Q2**NAT1 markMonitor

At most how many processes can be active inside a monitor at the same time?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT2 marksRace with S = 2

`x = 0`. W and X each do `x = x + 1`; Y and Z each do `x = x − 2`; each brackets its read-modify-write with `wait(S)` … `signal(S)`, and S starts at 2. Largest possible final value of x?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**NAT2 marksRace with S = 2

Same setup (S starts at 2). Smallest possible final value of x?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**NAT2 marksDistinct values

`B = 3`. P1: `C = B − 1; B = 2 * C;` P2: `D = 2 * B; B = D − 1;` (each line atomic, C and D local). How many different final values of B are possible?

Numerical answer: \_\_\_\_\_\_\_\_

### 10Rule Card

- Monitor: shared data + functions; one process active inside; condition variables wait/signal.
- x.wait releases the monitor; x.signal wakes one, or does nothing if none waits.
- Signal-and-wait vs signal-and-continue (re-check with while).
- Code analysis: shared/local → split → extremes → semaphore values → ME, deadlock, progress, starvation.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

monitorcondition variablewait and signal on conditionslost signal vs remembered Vsignal-and-waitsignal-and-continuemethod for analysing concurrent code

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. 0.
2. 1.
3. Yes.

#### Self-Test

**Q1** Answer: (A)1 mark

Condition variables have no memory.

- **(B) is wrong:** The caller continues.
- **(C) is wrong:** That is semaphore behaviour.
- **(D) is wrong:** It is legal.

Re-read: [Lesson 3.2.3](#l-3-2-3) — Monitors, and reasoning about concurrent code

**Q2** Answer: 11 mark

Mutual exclusion is built in.

Re-read: [Lesson 3.2.3](#l-3-2-3) — Monitors, and reasoning about concurrent code

**Q3** Answer: 22 marks

Two processes can race inside; lose both decrements.

Re-read: [Lesson 3.2.3](#l-3-2-3) — Monitors, and reasoning about concurrent code

**Q4** Answer: -42 marks

Lose both increments: −2 − 2.

Re-read: [Lesson 3.2.3](#l-3-2-3) — Monitors, and reasoning about concurrent code

**Q5** Answer: 42 marks

4, 5, 7 and 8.

Re-read: [Lesson 3.2.3](#l-3-2-3) — Monitors, and reasoning about concurrent code

Type next → [**LI-3.2** Chapter 3.2 Lock-in](#l-LI-3-2)

## 🔒Chapter 3.2 Lock-in — Semaphores and classic problems

Phase 3 › Concurrency & Synchronization › Chapter 3.2 Semaphores and classic problems

Phase 3Ch 3.2 Semaphores and classic problems

### ACompressed recap

🧾

Semaphore: wait (S--, block if S \< 0), signal (S++, wake if S ≤ 0); −k = k waiters; final = initial − waits + signals. Mutex 1, ordering 0, k resources k. Bounded buffer: mutex 1, empty N, full 0, counting wait before mutex. Readers–writers (first): first reader waits rw, last signals; writers starve. Philosophers: all-left deadlock; ≤ 4 at table, asymmetry, both-at-once; max ⌊n/2⌋ eat. Monitor: one active inside; condition signal lost if no waiter. Method: shared/local, split, extremes, semaphores, four questions.

### BMerged rule card

[3.2.1](#l-3-2-1) Semaphores: wait, signal, counting and binary semaphores

- wait/P: S--; if S \< 0 block. signal/V: S++; if S ≤ 0 wake one. Atomic.
- Negative value −k = k processes waiting. Final value = initial − waits + signals.
- Binary (mutex, starts 1) vs counting (starts k). Ordering semaphore starts 0.
- Opposite orders of waits can deadlock; LIFO queues can starve.

[3.2.2](#l-3-2-2) Classic problems: bounded buffer, readers–writers, dining philosophers

- Bounded buffer: mutex = 1, empty = N, full = 0; counting wait before mutex wait; signals in any order.
- Readers–writers (reader priority): first reader waits on rw, last reader signals rw; writers may starve.
- Dining philosophers: all left-first → deadlock; fixes: ≤ 4 at table, asymmetry, both-at-once. Max ⌊n/2⌋ eat together.

[3.2.3](#l-3-2-3) Monitors, and reasoning about concurrent code

- Monitor: shared data + functions; one process active inside; condition variables wait/signal.
- x.wait releases the monitor; x.signal wakes one, or does nothing if none waits.
- Signal-and-wait vs signal-and-continue (re-check with while).
- Code analysis: shared/local → split → extremes → semaphore values → ME, deadlock, progress, starvation.

### CInterleaved GATE-style questions

**Q1**NAT1 markArithmetic

A semaphore starts at 7; 20 wait and 15 signal operations follow. Final value?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT2 marksOutputs

s = 0, t = 0. P1: `print "A"; signal(s); wait(t); print "C";` P2: `wait(s); print "B"; signal(t);` How many different outputs are possible?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**MCQ1 markDeadlock

P1 does `wait(S); wait(Q);` and P2 does `wait(Q); wait(S);` (S = Q = 1). What can happen?

1. (A) Nothing can go wrong
2. (B) Mutual exclusion is violated
3. (C) Deadlock
4. (D) Both processes always finish

**Q4**MCQ1 markBounded buffer

In the bounded-buffer solution, which pair of lines can be swapped safely?

1. (A) None
2. (B) The consumer's `wait(full)` and `wait(mutex)`
3. (C) The producer's `wait(empty)` and `wait(mutex)`
4. (D) The producer's `signal(mutex)` and `signal(full)`

**Q5**NAT1 markInitial values

Bounded buffer of size 5: sum of the initial values of empty, full and mutex?

Numerical answer: \_\_\_\_\_\_\_\_

**Q6**MCQ1 markReaders–writers

In the first readers–writers solution, which reader releases the writers' semaphore?

1. (A) Every reader
2. (B) The writer itself
3. (C) The first reader
4. (D) The last reader to leave

**Q7**MCQ1 markMonitor

A process calls `x.wait()` inside a monitor. Which is true?

1. (A) It terminates the process
2. (B) It returns immediately if no one signalled before
3. (C) It releases the monitor and sleeps on x
4. (D) It keeps the monitor locked while sleeping

**Q8**NAT2 marksFinal values

`x = 5`. P1 runs `wait(s); x = x + 1; signal(s);` but P2 runs `x = x − 1;` without using s (s starts at 1). Statements are load/compute/store. How many different final values of x are possible?

Numerical answer: \_\_\_\_\_\_\_\_

### DAnswer Vault

🔐 Open the Answer Vault

**Q1** Answer: 21 mark

7 − 20 + 15.

Re-read: [Lesson 3.2.1](#l-3-2-1) — Semaphores: wait, signal, counting and binary semaphores

**Q2** Answer: 12 marks

Only ABC: B needs s, and C needs t from P2.

Re-read: [Lesson 3.2.1](#l-3-2-1) — Semaphores: wait, signal, counting and binary semaphores

**Q3** Answer: (C)1 mark

Each holds one and waits for the other.

- **(A) is wrong:** A bad interleaving exists.
- **(B) is wrong:** Each semaphore still admits one.
- **(D) is wrong:** Not always.

Re-read: [Lesson 3.2.1](#l-3-2-1) — Semaphores: wait, signal, counting and binary semaphores

**Q4** Answer: (D)1 mark

Signals never block.

- **(A) is wrong:** The signals can be swapped.
- **(B) is wrong:** Deadlock on an empty buffer.
- **(C) is wrong:** Deadlock on a full buffer.

Re-read: [Lesson 3.2.2](#l-3-2-2) — Classic problems: bounded buffer, readers–writers, dining philosophers

**Q5** Answer: 61 mark

5 + 0 + 1.

Re-read: [Lesson 3.2.2](#l-3-2-2) — Classic problems: bounded buffer, readers–writers, dining philosophers

**Q6** Answer: (D)1 mark

When read_count drops to 0.

- **(A) is wrong:** Only when the count is 0.
- **(B) is wrong:** Readers release it.
- **(C) is wrong:** The first reader acquires it.

Re-read: [Lesson 3.2.2](#l-3-2-2) — Classic problems: bounded buffer, readers–writers, dining philosophers

**Q7** Answer: (C)1 mark

Others can enter meanwhile.

- **(A) is wrong:** No.
- **(B) is wrong:** There is no remembered signal.
- **(D) is wrong:** That would block everyone.

Re-read: [Lesson 3.2.3](#l-3-2-3) — Monitors, and reasoning about concurrent code

**Q8** Answer: 32 marks

P2 ignores the lock, so the race remains: 4, 5 or 6.

Re-read: [Lesson 3.2.3](#l-3-2-3) — Monitors, and reasoning about concurrent code

Type next → [**CP-3** Phase 3 Checkpoint (15 questions)](#l-CP-3)

## ⏱️Phase 3 Checkpoint — Concurrency & Synchronization

Phase 3 › Concurrency & Synchronization

Phase 3

Phase 3 Checkpoint: 15 questions on synchronization.

⏱️

**15 questions · 20 marks · 45 minutes.** Negative marking on MCQ only: −1/3 mark for a wrong 1-mark MCQ, −2/3 for a wrong 2-mark MCQ. No negative marking for MSQ or NAT; MSQ has no partial credit.

**Q1**NAT1 markRace

`x = 10`. Thread 1 runs `x = x + 5` and thread 2 runs `x = x * 2` (each a load, a compute and a store). How many different final values are possible?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**MCQ1 markDefinition

A race condition is:

1. (A) a situation where the result depends on the order in which threads run
2. (B) a deadlock between two threads
3. (C) a hardware fault
4. (D) a scheduling algorithm

**Q3**NAT2 marksLoops

`x = 0`; two threads each execute `x++` 5 times. Largest possible final value?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**MCQ1 markStrict alternation

Strict alternation guarantees mutual exclusion but violates:

1. (A) nothing
2. (B) progress
3. (C) mutual exclusion
4. (D) atomicity of turn

**Q5**MCQ2 marksPeterson

Which line order is correct for Peterson's entry section of process i?

1. (A) `turn = j; flag[i] = true; while (flag[j] && turn == j);`
2. (B) `flag[i] = true; turn = j; while (flag[j] && turn == j);`
3. (C) `turn = i; while (turn == j); flag[i] = true;`
4. (D) `flag[i] = true; turn = i; while (flag[j] && turn == j);`

**Q6**MCQ1 markTSL

The test-and-set instruction:

1. (A) only works on one CPU
2. (B) returns the new value
3. (C) needs interrupts to be enabled
4. (D) sets the lock and returns the old value, atomically

**Q7**NAT1 markCAS

v = 9. `CAS(&v, 9, 2)` is called, then `CAS(&v, 9, 5)`. Final v?

Numerical answer: \_\_\_\_\_\_\_\_

**Q8**NAT1 markArithmetic

A semaphore starts at 4; then 9 wait and 3 signal operations are done (blocking version). How many processes are waiting?

Numerical answer: \_\_\_\_\_\_\_\_

**Q9**NAT2 marksOutputs

S = 1, T = 0. P1 runs twice: `wait(S); print "0"; signal(T);` P2 runs twice: `wait(T); print "1"; signal(S);` How many different outputs are possible?

Numerical answer: \_\_\_\_\_\_\_\_

**Q10**NAT2 marksOutputs

Same code with S = 1 and T = 1. How many different outputs are possible?

Numerical answer: \_\_\_\_\_\_\_\_

**Q11**MCQ1 markUse

A semaphore initialised to 0 is typically used for:

1. (A) ordering one event after another
2. (B) counting free buffer slots
3. (C) mutual exclusion
4. (D) nothing

**Q12**NAT1 markBounded buffer

Producer–consumer with a 10-slot buffer: after the producer adds 4 items and the consumer removes 1 (no one waiting), what is the value of `full`?

Numerical answer: \_\_\_\_\_\_\_\_

**Q13**MCQ1 markPhilosophers

All five philosophers pick up the left chopstick at the same moment. The result is:

1. (A) two philosophers eating
2. (B) mutual exclusion violated
3. (C) deadlock
4. (D) starvation of one philosopher only

**Q14**MCQ1 markMonitors

The main difference between `signal` on a condition variable and `signal` on a semaphore is that the condition variable's signal:

1. (A) needs busy waiting
2. (B) can wake all processes
3. (C) is lost if no process is waiting
4. (D) increments a counter

**Q15**NAT2 marksRace with semaphore

`x = 0`. W and X each do `x = x + 1`; Y and Z each do `x = x − 2`; each brackets its read-modify-write with `wait(S)` … `signal(S)`, and S starts at 1. Final value of x?

Numerical answer: \_\_\_\_\_\_\_\_

### ✓Answer Vault

🔐 Open the Answer Vault

**Q1** Answer: 41 mark

30, 25, 15, 20.

Re-read: [Lesson 3.1.1](#l-3-1-1) — Race conditions and the critical-section problem

**Q2** Answer: (A)1 mark

Timing-dependent results.

- **(B) is wrong:** Different problem.
- **(C) is wrong:** Software, not hardware.
- **(D) is wrong:** Not an algorithm.

Re-read: [Lesson 3.1.1](#l-3-1-1) — Race conditions and the critical-section problem

**Q3** Answer: 102 marks

No updates lost.

Re-read: [Lesson 3.1.1](#l-3-1-1) — Race conditions and the critical-section problem

**Q4** Answer: (B)1 mark

A free CS can be refused.

- **(A) is wrong:** Progress fails.
- **(C) is wrong:** That holds.
- **(D) is wrong:** Not a requirement.

Re-read: [Lesson 3.1.2](#l-3-1-2) — Software solutions: turn and flag attempts, Peterson's algorithm

**Q5** Answer: (B)2 marks

Flag first, then give away the turn.

- **(A) is wrong:** Swapped order breaks mutual exclusion.
- **(C) is wrong:** Not Peterson.
- **(D) is wrong:** Giving the turn to yourself with that test can let both in.

Re-read: [Lesson 3.1.2](#l-3-1-2) — Software solutions: turn and flag attempts, Peterson's algorithm

**Q6** Answer: (D)1 mark

Atomic read-and-set.

- **(A) is wrong:** Works on multiprocessors too.
- **(B) is wrong:** Returns the old value.
- **(C) is wrong:** Unrelated.

Re-read: [Lesson 3.1.3](#l-3-1-3) — Hardware help: test-and-set, compare-and-swap, spinlocks

**Q7** Answer: 21 mark

The second call finds 2, not 9.

Re-read: [Lesson 3.1.3](#l-3-1-3) — Hardware help: test-and-set, compare-and-swap, spinlocks

**Q8** Answer: 21 mark

4 − 9 + 3 = −2.

Re-read: [Lesson 3.2.1](#l-3-2-1) — Semaphores: wait, signal, counting and binary semaphores

**Q9** Answer: 12 marks

Only 0101: the semaphores force alternation.

Re-read: [Lesson 3.2.1](#l-3-2-1) — Semaphores: wait, signal, counting and binary semaphores

**Q10** Answer: 42 marks

0101, 0110, 1001, 1010.

Re-read: [Lesson 3.2.1](#l-3-2-1) — Semaphores: wait, signal, counting and binary semaphores

**Q11** Answer: (A)1 mark

The waiter blocks until signalled.

- **(B) is wrong:** Starts at N.
- **(C) is wrong:** Mutex starts at 1.
- **(D) is wrong:** It is useful.

Re-read: [Lesson 3.2.1](#l-3-2-1) — Semaphores: wait, signal, counting and binary semaphores

**Q12** Answer: 31 mark

0 + 4 − 1.

Re-read: [Lesson 3.2.2](#l-3-2-2) — Classic problems: bounded buffer, readers–writers, dining philosophers

**Q13** Answer: (C)1 mark

Everyone holds one and waits for one.

- **(A) is wrong:** Nobody can eat.
- **(B) is wrong:** Each chopstick is held by one.
- **(D) is wrong:** Everyone is stuck.

Re-read: [Lesson 3.2.2](#l-3-2-2) — Classic problems: bounded buffer, readers–writers, dining philosophers

**Q14** Answer: (C)1 mark

No memory.

- **(A) is wrong:** No.
- **(B) is wrong:** signal wakes one.
- **(D) is wrong:** That is the semaphore.

Re-read: [Lesson 3.2.3](#l-3-2-3) — Monitors, and reasoning about concurrent code

**Q15** Answer: -22 marks

S = 1 removes the race.

Re-read: [Lesson 3.2.3](#l-3-2-3) — Monitors, and reasoning about concurrent code

Type next → [**4.1.1** Deadlock: the four conditions and resource-allocation graphs](#l-4-1-1)

# 🧱Phase 4 — Deadlock

## 📄Lesson 4.1.1 — Deadlock: the four conditions and resource-allocation graphs

Phase 4 › Deadlock › Chapter 4.1 Deadlock › Topic 4.1.1

Phase 4Ch 4.1 DeadlockTopic 4.1.1GATE weight: High≈ 45 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. What did the two-flag attempt suffer from? from [Lesson 3.1.2](#l-3-1-2)
2. What happens if all five philosophers pick up the left chopstick? from [Lesson 3.2.2](#l-3-2-2)
3. P1 does wait(S); wait(Q) and P2 does wait(Q); wait(S). What can happen? from [Lesson 3.2.1](#l-3-2-1)

### 1The Hook

🎣

Four cars reach a crossroads at the same moment; each waits for the car on its right to go first. Nobody moves, ever. That is a **deadlock**, and we have already met it three times in Phase 3. This phase studies it properly: the four conditions that must all be true for it to happen, a drawing that shows it (the resource-allocation graph), and what an OS can do about it. GATE asks a deadlock question nearly every year, often a numerical one.

### 2Predict First

🤔

Process P1 holds the printer and wants the scanner. Process P2 holds the scanner and wants the printer. Neither will let go of what it has. What happens?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

**Deadlock**: each waits for something the other holds, for ever.

🗣️

In plain words

A set of processes is deadlocked when each one is waiting for something that only another process **in the same set** can give. Since they are all waiting, nobody gives anything, and they wait for ever. A deadlock needs four things to be true together; remove any one and it cannot happen.

#### 1. Resources

A **resource** is anything a process must get before using: a printer, a file, a lock, memory. A resource type may have several identical **instances** (e.g. 3 printers). A process uses a resource in three steps: **request** (wait if not available) → **use** → **release**.

#### 2. The four necessary conditions (Coffman conditions)

All four must hold at the same time for a deadlock:

1. **Mutual exclusion**: at least one resource can be used by only one process at a time.
2. **Hold and wait**: a process holds at least one resource while waiting for another.
3. **No pre-emption**: a resource can't be taken away; the holder must release it voluntarily.
4. **Circular wait**: there is a cycle P1 → P2 → … → Pn → P1 where each waits for a resource held by the next.

Break **any one** and deadlock is impossible.

#### 3. Resource-allocation graph (RAG)

- A **circle** for each process, a **box** for each resource type, with one dot per instance.
- **Request edge** P → R: P is waiting for R.
- **Assignment edge** R → P: an instance of R is held by P.

Reading the graph:

| Graph | Meaning |
| --- | --- |
| No cycle | **No deadlock** |
| Cycle, every resource has **one instance** | **Deadlock** (certain) |
| Cycle, some resource has **several instances** | Deadlock **possible**, not certain |

With several instances, check whether some process in the cycle can still finish: a process outside the cycle (or one whose requests can be met) may release an instance and break the wait.

#### 4. Deadlock vs starvation

- **Deadlock**: a group waits for each other; nobody can ever proceed.
- **Starvation**: one process waits indefinitely while others keep running (e.g. low priority without aging).

Deadlock implies the waiting processes starve, but starvation can happen without deadlock.

### 4Visual

In (b), P3 is not waiting. When it finishes it releases its R1, P2 takes it and finishes, then P1 gets R2.

### 5Worked Examples

Example 1 Easy

P1 holds R1 and requests R2; P2 holds R2 and requests R1. Each resource has one instance. Deadlock?

Solution

**Yes**: the graph has the cycle P1 → R2 → P2 → R1 → P1 and every resource has one instance.

Example 2 Medium

Same as Easy, but R1 has two instances and the second one is held by P3, which is not waiting for anything. Deadlock?

Solution

**No.** P3 finishes and releases its R1; P2 gets it, finishes, and releases R2; then P1 gets R2.

Example 3 GATE

Which condition is broken if the OS forces every process to request **all** its resources at once, before it starts?

Solution

**Hold and wait**: a process never holds something while waiting for more.

### 6GATE Traps

⚠️

- All **four** conditions are necessary; a deadlock needs every one of them.
- A cycle means deadlock **only** when every resource in it has a single instance.
- Edge directions: request P → R, assignment R → P.
- Starvation is not the same as deadlock.

### 7Memory Hook

🧠

**"Mutual exclusion, Hold and wait, No pre-emption, Circular wait: all four, or no deadlock."** (M-H-N-C: "My Hands Never Cooperate".)

### 8Connect the Dots

If all four conditions are needed, the OS can make sure one of them never holds (**prevention**), or carefully refuse requests that might lead to trouble (**avoidance**, the banker's algorithm). That is the next lesson.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**MSQ2 marksConditions

Which of these are necessary conditions for deadlock?

1. (A) Hold and wait
2. (B) Pre-emption of resources
3. (C) Circular wait
4. (D) Mutual exclusion

**Q2**MCQ1 markRAG

A resource-allocation graph has a cycle, and every resource type has exactly one instance. Then:

1. (A) the graph is invalid
2. (B) there is no deadlock
3. (C) there may or may not be a deadlock
4. (D) there is a deadlock

**Q3**MCQ1 markRAG edges

In a resource-allocation graph, an edge from resource R to process P means:

1. (A) R is waiting for P
2. (B) an instance of R is held by P
3. (C) P is requesting R
4. (D) P has released R

**Q4**MCQ1 markStarvation

Which statement is true?

1. (A) Deadlocked processes cannot proceed, but starvation can happen without deadlock
2. (B) Deadlock needs only circular wait
3. (C) Starvation and deadlock are the same thing
4. (D) Every starvation is a deadlock

**Q5**MCQ2 marksMultiple instances

R1 has 2 instances held by P1 and P3; R2 has 1 instance held by P2. P1 requests R2, P2 requests R1, and P3 requests nothing. Is the system deadlocked?

1. (A) Cannot be decided
2. (B) Yes, because there is a cycle
3. (C) No, because P3 can finish and release R1
4. (D) Yes, because R2 has one instance

### 10Rule Card

- Deadlock: each process in a set waits for something only another in the set can give.
- Four necessary conditions: mutual exclusion, hold and wait, no pre-emption, circular wait.
- RAG: request P → R, assignment R → P. No cycle → no deadlock; cycle + single instances → deadlock; cycle + multiple instances → maybe.
- Starvation ≠ deadlock.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

deadlockresources and instancesrequest–use–releasemutual exclusionhold and waitno pre-emptioncircular waitresource-allocation graphrequest and assignment edgescycles with single vs multiple instancesdeadlock vs starvation

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. Deadlock: both wait for ever.
2. Deadlock.
3. Deadlock.

#### Self-Test

**Q1** Answer: (A) (C) (D)2 marks

The fourth condition is **no** pre-emption.

- **(B) is wrong:** Pre-emption would let the OS break a deadlock; the condition is the absence of it.

Re-read: [Lesson 4.1.1](#l-4-1-1) — Deadlock: the four conditions and resource-allocation graphs

**Q2** Answer: (D)1 mark

Single instances + cycle = deadlock.

- **(A) is wrong:** Cycles are allowed.
- **(B) is wrong:** A cycle with single instances is a deadlock.
- **(C) is wrong:** That is the multi-instance case.

Re-read: [Lesson 4.1.1](#l-4-1-1) — Deadlock: the four conditions and resource-allocation graphs

**Q3** Answer: (B)1 mark

Assignment edge.

- **(A) is wrong:** Resources don't wait.
- **(C) is wrong:** That is P → R.
- **(D) is wrong:** Released resources have no edge.

Re-read: [Lesson 4.1.1](#l-4-1-1) — Deadlock: the four conditions and resource-allocation graphs

**Q4** Answer: (A)1 mark

A low-priority process can starve while others run.

- **(B) is wrong:** All four conditions.
- **(C) is wrong:** Different ideas.
- **(D) is wrong:** Not every starvation.

Re-read: [Lesson 4.1.1](#l-4-1-1) — Deadlock: the four conditions and resource-allocation graphs

**Q5** Answer: (C)2 marks

P3's release lets P2 and then P1 finish.

- **(A) is wrong:** It can be decided.
- **(B) is wrong:** A cycle is not enough with multiple instances.
- **(D) is wrong:** P2 can still finish once it gets R1.

Re-read: [Lesson 4.1.1](#l-4-1-1) — Deadlock: the four conditions and resource-allocation graphs

Type next → [**4.1.2** Prevention and avoidance: safe states and the banker's algorithm](#l-4-1-2)

## 📄Lesson 4.1.2 — Prevention and avoidance: safe states and the banker's algorithm

Phase 4 › Deadlock › Chapter 4.1 Deadlock › Topic 4.1.2

Phase 4Ch 4.1 DeadlockTopic 4.1.2GATE weight: High≈ 55 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. The four deadlock conditions? from [Lesson 4.1.1](#l-4-1-1)
2. Cycle in a RAG with multiple instances means? from [Lesson 4.1.1](#l-4-1-1)
3. What does a counting semaphore initialised to k allow? from [Lesson 3.2.1](#l-3-2-1)

### 1The Hook

🎣

A bank has ₹10 lakh to lend. Three businesses each have a credit limit. The banker never lends money if, afterwards, there would be no way for every business to finish its project and repay. That cautious banker is exactly the **banker's algorithm**, and it is GATE's favourite deadlock question: build the Need matrix, then find a safe sequence.

### 2Predict First

🤔

12 printers. A holds 5 and may need up to 10; B holds 2 and may need up to 4; C holds 2 and may need up to 9. 3 printers are free. Can everyone surely finish?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

**Yes.** Give B its 2 more (B finishes, returns 4 → 5 free), then A its 5 more (→ 10 free), then C its 7 more. That order is a **safe sequence**.

🗣️

In plain words

**Prevention** designs the system so that one of the four conditions can never be true. **Avoidance** lets processes ask for resources freely, but before granting a request the OS checks: "after this, is there still some order in which everyone can finish?" If yes the state is **safe** and the request is granted; if not, the process waits.

#### 1. Prevention: break one condition

| Condition | How to break it | Cost |
| --- | --- | --- |
| Mutual exclusion | make resources sharable (e.g. spool printer output) | impossible for many resources |
| Hold and wait | request **everything at the start**, or release all before asking for more | poor utilisation, starvation |
| No pre-emption | if a request can't be met, take away what the process holds | only for resources whose state can be saved (CPU, memory) |
| Circular wait | number the resource types; always request in **increasing order** | the most practical method |

#### 2. Safe state

A state is **safe** if there is at least one order (a **safe sequence**) in which every process can get its maximum demand, finish and release everything.

- Safe → no deadlock is possible if the OS keeps the state safe.
- **Unsafe ≠ deadlocked**: unsafe only means a deadlock *might* happen if processes ask for their maximum.

#### 3. Banker's algorithm: data

For n processes and m resource types:

- **Available\[m\]**: free instances of each type.
- **Max\[n\]\[m\]**: maximum each process may ever need.
- **Allocation\[n\]\[m\]**: what each process holds now.
- **Need = Max − Allocation**: what each may still ask for.

#### 4. Safety algorithm

1. Work = Available; all processes unfinished.
2. Find an unfinished process with **Need ≤ Work** (every type). If none, stop.
3. Pretend it runs to the end: **Work = Work + its Allocation**; mark it finished. Go to 2.
4. If every process finished, the state is **safe** (the order found is a safe sequence); otherwise **unsafe**.

#### 5. Resource-request algorithm (process i asks for Request)

1. If Request > Need_i → error (asked for more than declared).
2. If Request > Available → wait.
3. **Pretend** to grant: Available −= Request, Allocation_i += Request, Need_i −= Request. Run the safety algorithm. Safe → grant; unsafe → undo and make the process wait.

#### 6. Worked example (resource types A, B, C; totals 8, 5, 5)

| Process | Allocation | Max | Need |
| --- | --- | --- | --- |
| P0 | 1 1 0 | 5 3 2 | 4 2 2 |
| P1 | 2 0 1 | 3 2 2 | 1 2 1 |
| P2 | 1 2 1 | 4 2 3 | 3 0 2 |
| P3 | 0 1 1 | 2 2 2 | 2 1 1 |
| P4 | 2 0 0 | 4 3 1 | 2 3 1 |

Available = (2, 1, 2).

- Work (2,1,2): only P3's need (2,1,1) fits → Work = (2,2,3).
- P1's need (1,2,1) fits → (4,2,4). P0's (4,2,2) fits → (5,3,4). P2's (3,0,2) fits → (6,5,5). P4's (2,3,1) fits → (8,5,5).
- Safe sequence **P3, P1, P0, P2, P4** → the state is **safe**.

Request: P1 asks for (1,0,1). It is ≤ Need and ≤ Available. Pretend: Available (1,1,1), P1's need (0,2,0). Now no process's need fits in (1,1,1): **unsafe → P1 must wait**.

### 4Visual

```
Safety check = "can somebody finish with what is free?"

Work (2,1,2)  --P3 finishes-->  (2,2,3)  --P1-->  (4,2,4)  --P0-->  (5,3,4)
              --P2-->  (6,5,5)  --P4-->  (8,5,5) = all resources back: SAFE

each step: Need of that process <= Work, then Work += its Allocation
```

### 5Worked Examples

Example 1 Easy

A process has Max (7, 5, 3) and Allocation (0, 1, 0). What is its Need?

Solution

(7 − 0, 5 − 1, 3 − 0) = **(7, 4, 3)**.

Example 2 Medium

13 units of one resource. A holds 6 (max 9), B holds 2 (max 5), C holds 2 (max 8). Is the state safe?

Solution

Free = 13 − 10 = 3. Needs: A 3, B 3, C 6. A finishes (3 ≤ 3) → 9 free; B → 11; C (6) → 13. **Safe**, e.g. A, B, C.

Example 3 GATE

In the Medium example, C asks for 1 more unit. Should it be granted?

Solution

Pretend: free 2; needs A 3, B 3, C 5. Nobody's need fits in 2: **unsafe**, so **no** (C waits). (If B asked for 1 instead: free 2, B's need 2 fits, and the state stays safe.)

### 6GATE Traps

⚠️

- Need = **Max − Allocation**, not Max − Available.
- Compare Need with Work for **every** resource type.
- After a process "finishes", add its **Allocation** (not its Need or Max) to Work.
- Unsafe does not mean deadlocked; it means the OS can no longer guarantee safety.
- There may be several safe sequences; any one proves safety.

### 7Memory Hook

🧠

**"Need = Max − Alloc. Find someone whose Need fits, let them finish, collect their Alloc, repeat."**

### 8Connect the Dots

Avoidance needs to know every process's maximum in advance, which real systems rarely do. The last deadlock lesson lets deadlocks happen, **detects** them and **recovers**, and gives the quick formula for how many resources make deadlock impossible.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**NAT1 markNeed

A process has Max (5, 3, 2) and Allocation (1, 1, 0) for types A, B, C. Sum of its Need values?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**MCQ1 markPrevention

Requiring processes to request resource types in increasing numerical order prevents deadlock by breaking:

1. (A) hold and wait
2. (B) no pre-emption
3. (C) mutual exclusion
4. (D) circular wait

**Q3**MCQ2 marksSafe sequence

Worked example of this lesson (Available (2,1,2)): which process is the only one that can run first in a safe sequence?

1. (A) P1
2. (B) P3
3. (C) P0
4. (D) P4

**Q4**MCQ2 marksRequest

In the worked example, P3 asks for (1, 1, 0). What does the banker's algorithm do?

1. (A) Grants it: the new state is safe
2. (B) Makes P3 wait: the new state is unsafe
3. (C) Makes P3 wait: not enough available
4. (D) Refuses: it exceeds P3's need

**Q5**MCQ1 markUnsafe

An unsafe state means:

1. (A) the banker's algorithm has failed
2. (B) a deadlock may occur, and the OS can't guarantee it won't
3. (C) no process can ever run
4. (D) the system is deadlocked

### 10Rule Card

- Prevention breaks a condition: all-at-once requests (hold and wait), pre-emption, resource ordering (circular wait).
- Safe state: some order lets everyone finish. Unsafe ≠ deadlock.
- Banker's: Need = Max − Allocation; Work = Available; pick Need ≤ Work; Work += Allocation; all finish → safe.
- Request: ≤ Need, ≤ Available, pretend, check safety; grant only if safe.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

deadlock preventionresource orderingdeadlock avoidancesafe statesafe sequenceunsafe statebanker's algorithmAvailable, Max, Allocation, Needsafety algorithmresource-request algorithm

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. Mutual exclusion, hold and wait, no pre-emption, circular wait.
2. Deadlock possible, not certain.
3. Up to k processes at a time.

#### Self-Test

**Q1** Answer: 81 mark

Need (4, 2, 2).

Re-read: [Lesson 4.1.2](#l-4-1-2) — Prevention and avoidance: safe states and the banker's algorithm

**Q2** Answer: (D)1 mark

A cycle would need someone to request a lower-numbered type.

- **(A) is wrong:** Processes still hold while waiting.
- **(B) is wrong:** Nothing is taken away.
- **(C) is wrong:** Resources are still exclusive.

Re-read: [Lesson 4.1.2](#l-4-1-2) — Prevention and avoidance: safe states and the banker's algorithm

**Q3** Answer: (B)2 marks

Only P3's need (2,1,1) fits in (2,1,2).

- **(A) is wrong:** Needs 2 of B.
- **(C) is wrong:** Needs 4 of A.
- **(D) is wrong:** Needs 3 of B.

Re-read: [Lesson 4.1.2](#l-4-1-2) — Prevention and avoidance: safe states and the banker's algorithm

**Q4** Answer: (A)2 marks

Available becomes (1,0,2), P3's need (1,0,1) fits, and the rest follow as before.

- **(B) is wrong:** A safe sequence still exists.
- **(C) is wrong:** (1,1,0) ≤ (2,1,2).
- **(D) is wrong:** (1,1,0) ≤ (2,1,1).

Re-read: [Lesson 4.1.2](#l-4-1-2) — Prevention and avoidance: safe states and the banker's algorithm

**Q5** Answer: (B)1 mark

Unsafe is a warning, not a deadlock.

- **(A) is wrong:** It reports the state correctly.
- **(C) is wrong:** Some may still run.
- **(D) is wrong:** Not necessarily.

Re-read: [Lesson 4.1.2](#l-4-1-2) — Prevention and avoidance: safe states and the banker's algorithm

Type next → [**4.1.3** Detection, recovery, and the minimum-resources formula](#l-4-1-3)

## 📄Lesson 4.1.3 — Detection, recovery, and the minimum-resources formula

Phase 4 › Deadlock › Chapter 4.1 Deadlock › Topic 4.1.3

Phase 4Ch 4.1 DeadlockTopic 4.1.3GATE weight: High≈ 45 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. Need = ? from [Lesson 4.1.2](#l-4-1-2)
2. Does an unsafe state mean deadlock? from [Lesson 4.1.2](#l-4-1-2)
3. A cycle in a RAG with single-instance resources means? from [Lesson 4.1.1](#l-4-1-1)

### 1The Hook

🎣

Most operating systems (Windows, Linux) do not run the banker's algorithm: it costs time and needs maximum demands in advance. Some simply ignore deadlocks and let the user restart a frozen program. Others check every so often whether a deadlock has formed and then break it. And there is one very quick calculation GATE loves: "how many resources make deadlock **impossible**?"

### 2Predict First

🤔

3 processes each need at most 2 units of a resource. With 3 units, can they deadlock? With 4?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

With **3**: each grabs 1, all wait for a second unit that never comes → deadlock. With **4**: whatever happens, someone can get 2 units, finish and release → **no deadlock**.

🗣️

In plain words

**Detection** runs a check like the banker's safety test, but with the processes' **current requests** instead of their maximum needs: anyone whose current request can be met is assumed to finish and release. Whoever can never finish is deadlocked. **Recovery** then kills processes or takes resources away until the deadlock is gone.

#### 1. Four strategies overall

1. **Prevention** (Lesson 4.1.2).
2. **Avoidance** (banker's).
3. **Detection and recovery** (this lesson).
4. **Ignore it** (the "ostrich" approach): used by most general-purpose OSes because deadlocks are rare.

#### 2. Detection with single instances: wait-for graph

Remove the resource boxes from the RAG: draw Pi → Pj if Pi waits for a resource held by Pj. **A cycle in the wait-for graph means deadlock.**

#### 3. Detection with multiple instances

Data: Available, Allocation, **Request** (what each process is asking for right now).

1. Work = Available. A process holding nothing is marked finished.
2. Find an unfinished process with **Request ≤ Work**; then Work += its Allocation; mark finished; repeat.
3. Processes still unfinished are **deadlocked**.

Example (types A, B, C; Available (0,0,0)):

| Process | Allocation | Request |
| --- | --- | --- |
| P0 | 0 1 0 | 0 0 1 |
| P1 | 1 0 1 | 0 1 0 |
| P2 | 2 1 0 | 1 0 0 |
| P3 | 0 0 1 | 0 0 0 |
| P4 | 1 1 1 | 1 0 1 |

P3 needs nothing → Work (0,0,1). P0 → (0,1,1). P1 → (1,1,2). P2 → (3,2,2). P4 → (4,3,3). Everyone finishes: **no deadlock**. If P0's request were (0,1,1) instead: after P3, Work = (0,0,1) and nobody else fits → **P0, P1, P2, P4 are deadlocked**.

#### 4. Recovery

- **Terminate processes**: all deadlocked ones at once (simple, expensive), or one at a time until the cycle breaks (re-run detection each time).
- **Pre-empt resources**: pick a **victim**, take its resources, **roll it back** to a safe point; make sure the same process is not always the victim (starvation).

#### 5. How many resources make deadlock impossible?

One resource type with R instances; process i needs at most kᵢ. Worst case: every process holds kᵢ − 1 and waits for one more. If even then one unit is left over, someone finishes. So: **Deadlock is impossible ⟺ R ≥ Σ(kᵢ − 1) + 1.**

- n processes each needing k: no deadlock ⟺ R ≥ n(k − 1) + 1.
- Needs 3, 4, 5: R ≥ 2 + 3 + 4 + 1 = **10**.
- R = 6, each process needs 2: deadlock possible once n(2 − 1) ≥ 6, i.e. **n ≥ 6**.

### 4Visual

```
Why sum(k_i - 1) + 1 ?   Needs 3, 4, 5  (worst case: everyone one short)

P1 holds 2 (needs 3)   ██░
P2 holds 3 (needs 4)   ███░
P3 holds 4 (needs 5)   ████░
                       held = 2 + 3 + 4 = 9
With R = 9: nothing free  -> all wait: DEADLOCK possible
With R = 10: 1 unit free  -> someone completes, releases, everyone follows
```

### 5Worked Examples

Example 1 Easy

4 processes each need at most 3 units. Minimum number of units that makes deadlock impossible?

Solution

4 × (3 − 1) + 1 = **9**.

Example 2 Medium

A system has 13 units; each process needs at most 4. What is the largest number of processes that can never deadlock?

Solution

n(4 − 1) + 1 ≤ 13 → 3n ≤ 12 → n ≤ **4**.

Example 3 GATE

3 processes share 4 units of one resource; each may request up to K units. Largest K that guarantees no deadlock?

Solution

3(K − 1) + 1 ≤ 4 → K − 1 ≤ 1 → **K = 2**.

### 6GATE Traps

⚠️

- The formula is Σ(kᵢ − **1**) + **1**, not Σkᵢ.
- Detection uses the current **Request**, avoidance uses **Need** (= Max − Allocation).
- A process that holds nothing can't be part of a deadlock.
- Wait-for graph only works when every resource has a single instance.

### 7Memory Hook

🧠

**"Everyone one short, plus one spare: Σ(k − 1) + 1."**

### 8Connect the Dots

Phase 4 is complete. Deadlocks are about resources in general; the most important resource of all is **memory**. Phase 5 covers how the OS shares memory: paging, page tables, TLBs and virtual memory.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**NAT1 markMinimum resources

Processes P1, P2, P3 need at most 3, 4 and 5 units of one resource. Minimum number of units for which deadlock is impossible?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT1 markMinimum resources

3 processes each need at most 2 units. Minimum number of units that rules out deadlock?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT2 marksProcesses

A system has 6 identical units, and every process needs at most 2. What is the smallest number of processes that could deadlock?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**NAT2 marksDetection

In this lesson's detection example, P0's request is changed to (0, 1, 1). How many processes are deadlocked?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**MCQ1 markWait-for graph

A wait-for graph is used for deadlock detection when:

1. (A) the banker's algorithm is running
2. (B) there are no cycles
3. (C) resource types have many instances
4. (D) every resource type has a single instance

### 10Rule Card

- Strategies: prevention, avoidance, detection + recovery, ignore (ostrich).
- Single instances: wait-for graph cycle = deadlock. Multiple: matrix detection with Request ≤ Work.
- Recovery: kill all / one at a time; pre-empt with victim + rollback (avoid starving one victim).
- No deadlock ⟺ R ≥ Σ(kᵢ − 1) + 1; n equal processes: R ≥ n(k − 1) + 1.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

ostrich approachwait-for graphdeadlock detection algorithmRequest matrixrecovery by terminationrecovery by pre-emptionvictim selection and rollbackminimum resources Σ(k − 1) + 1

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. Max − Allocation.
2. No: deadlock is possible, not certain.
3. Deadlock.

#### Self-Test

**Q1** Answer: 101 mark

2 + 3 + 4 + 1.

Re-read: [Lesson 4.1.3](#l-4-1-3) — Detection, recovery, and the minimum-resources formula

**Q2** Answer: 41 mark

3 × 1 + 1.

Re-read: [Lesson 4.1.3](#l-4-1-3) — Detection, recovery, and the minimum-resources formula

**Q3** Answer: 62 marks

n(2 − 1) ≥ 6.

Re-read: [Lesson 4.1.3](#l-4-1-3) — Detection, recovery, and the minimum-resources formula

**Q4** Answer: 42 marks

Only P3 can finish; P0, P1, P2 and P4 are stuck.

Re-read: [Lesson 4.1.3](#l-4-1-3) — Detection, recovery, and the minimum-resources formula

**Q5** Answer: (D)1 mark

Cycle ⟺ deadlock only with single instances.

- **(A) is wrong:** Unrelated.
- **(B) is wrong:** Detection looks for cycles.
- **(C) is wrong:** Needs the matrix algorithm.

Re-read: [Lesson 4.1.3](#l-4-1-3) — Detection, recovery, and the minimum-resources formula

Type next → [**LI-4.1** Chapter 4.1 Lock-in](#l-LI-4-1)

## 🔒Chapter 4.1 Lock-in — Deadlock

Phase 4 › Deadlock › Chapter 4.1 Deadlock

Phase 4Ch 4.1 Deadlock

### ACompressed recap

🧾

Four conditions (mutual exclusion, hold and wait, no pre-emption, circular wait). RAG: request P → R, assignment R → P; cycle + single instances = deadlock; multiple instances = maybe. Prevention: break a condition (resource ordering breaks circular wait). Avoidance: banker's, Need = Max − Allocation, safe sequence; unsafe ≠ deadlock. Detection: Request ≤ Work; wait-for graph for single instances. No deadlock ⟺ R ≥ Σ(kᵢ − 1) + 1.

### BMerged rule card

[4.1.1](#l-4-1-1) Deadlock: the four conditions and resource-allocation graphs

- Deadlock: each process in a set waits for something only another in the set can give.
- Four necessary conditions: mutual exclusion, hold and wait, no pre-emption, circular wait.
- RAG: request P → R, assignment R → P. No cycle → no deadlock; cycle + single instances → deadlock; cycle + multiple instances → maybe.
- Starvation ≠ deadlock.

[4.1.2](#l-4-1-2) Prevention and avoidance: safe states and the banker's algorithm

- Prevention breaks a condition: all-at-once requests (hold and wait), pre-emption, resource ordering (circular wait).
- Safe state: some order lets everyone finish. Unsafe ≠ deadlock.
- Banker's: Need = Max − Allocation; Work = Available; pick Need ≤ Work; Work += Allocation; all finish → safe.
- Request: ≤ Need, ≤ Available, pretend, check safety; grant only if safe.

[4.1.3](#l-4-1-3) Detection, recovery, and the minimum-resources formula

- Strategies: prevention, avoidance, detection + recovery, ignore (ostrich).
- Single instances: wait-for graph cycle = deadlock. Multiple: matrix detection with Request ≤ Work.
- Recovery: kill all / one at a time; pre-empt with victim + rollback (avoid starving one victim).
- No deadlock ⟺ R ≥ Σ(kᵢ − 1) + 1; n equal processes: R ≥ n(k − 1) + 1.

### CInterleaved GATE-style questions

**Q1**MCQ1 markConditions

Which condition says a resource can't be taken away from the process holding it?

1. (A) No pre-emption
2. (B) Circular wait
3. (C) Hold and wait
4. (D) Mutual exclusion

**Q2**MCQ1 markRAG

A resource-allocation graph has no cycle. Then:

1. (A) the system is unsafe
2. (B) the system is deadlocked
3. (C) the system is not deadlocked
4. (D) it depends on the number of instances

**Q3**NAT2 marksBanker's

One resource, 12 units. A holds 5 (max 10), B holds 2 (max 4), C holds 2 (max 9). How many units are free?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**MCQ2 marksBanker's

In the same state (12 units; A 5/10, B 2/4, C 2/9), C asks for 1 more unit. What happens?

1. (A) Granted: still safe
2. (B) C waits: the new state would be unsafe
3. (C) Granted: banker's never refuses
4. (D) Error: exceeds C's maximum

**Q5**MCQ1 markPrevention

Making a process request all its resources before it starts breaks:

1. (A) hold and wait
2. (B) mutual exclusion
3. (C) circular wait
4. (D) no pre-emption

**Q6**NAT1 markMinimum resources

5 processes each need at most 3 units. Minimum units so that deadlock can never occur?

Numerical answer: \_\_\_\_\_\_\_\_

**Q7**NAT2 marksMaximum K

4 processes share 9 units; each needs at most K. Largest K that guarantees no deadlock?

Numerical answer: \_\_\_\_\_\_\_\_

**Q8**MCQ1 markDetection

In the detection algorithm, a process is assumed able to finish when:

1. (A) it has the highest priority
2. (B) its Allocation ≤ Work
3. (C) its Max ≤ Work
4. (D) its current Request ≤ Work

### DAnswer Vault

🔐 Open the Answer Vault

**Q1** Answer: (A)1 mark

Only voluntary release.

- **(B) is wrong:** About the cycle.
- **(C) is wrong:** About holding while waiting.
- **(D) is wrong:** About sharing.

Re-read: [Lesson 4.1.1](#l-4-1-1) — Deadlock: the four conditions and resource-allocation graphs

**Q2** Answer: (C)1 mark

No cycle, no deadlock.

- **(A) is wrong:** Unrelated statement.
- **(B) is wrong:** Needs a cycle.
- **(D) is wrong:** Only matters when there is a cycle.

Re-read: [Lesson 4.1.1](#l-4-1-1) — Deadlock: the four conditions and resource-allocation graphs

**Q3** Answer: 32 marks

12 − 9.

Re-read: [Lesson 4.1.2](#l-4-1-2) — Prevention and avoidance: safe states and the banker's algorithm

**Q4** Answer: (B)2 marks

Free 2: B finishes (free 4), but A needs 5 and C needs 6.

- **(A) is wrong:** No safe sequence remains.
- **(C) is wrong:** It refuses unsafe requests.
- **(D) is wrong:** 3 ≤ 9.

Re-read: [Lesson 4.1.2](#l-4-1-2) — Prevention and avoidance: safe states and the banker's algorithm

**Q5** Answer: (A)1 mark

It never holds while waiting.

- **(B) is wrong:** Resources are still exclusive.
- **(C) is wrong:** Not directly.
- **(D) is wrong:** Nothing is pre-empted.

Re-read: [Lesson 4.1.2](#l-4-1-2) — Prevention and avoidance: safe states and the banker's algorithm

**Q6** Answer: 111 mark

5 × 2 + 1.

Re-read: [Lesson 4.1.3](#l-4-1-3) — Detection, recovery, and the minimum-resources formula

**Q7** Answer: 32 marks

4(K − 1) + 1 ≤ 9 → K ≤ 3.

Re-read: [Lesson 4.1.3](#l-4-1-3) — Detection, recovery, and the minimum-resources formula

**Q8** Answer: (D)1 mark

Detection uses current requests.

- **(A) is wrong:** Priority is irrelevant.
- **(B) is wrong:** Allocation is what it gives back.
- **(C) is wrong:** That is avoidance thinking (and uses Need).

Re-read: [Lesson 4.1.3](#l-4-1-3) — Detection, recovery, and the minimum-resources formula

Type next → [**CP-4** Phase 4 Checkpoint (15 questions)](#l-CP-4)

## ⏱️Phase 4 Checkpoint — Deadlock

Phase 4 › Deadlock

Phase 4

Phase 4 Checkpoint: 15 questions on deadlock.

⏱️

**15 questions · 22 marks · 40 minutes.** Negative marking on MCQ only: −1/3 mark for a wrong 1-mark MCQ, −2/3 for a wrong 2-mark MCQ. No negative marking for MSQ or NAT; MSQ has no partial credit.

**Q1**MSQ2 marksConditions

Which of these, if prevented, make deadlock impossible?

1. (A) Context switching
2. (B) Circular wait
3. (C) Hold and wait
4. (D) Mutual exclusion

**Q2**MCQ1 markRAG

An edge from process P to resource R in a resource-allocation graph means:

1. (A) R is free
2. (B) P has finished with R
3. (C) P is waiting for R
4. (D) P holds R

**Q3**MCQ2 marksMultiple instances

A RAG contains a cycle and one of the resources in it has 2 instances. Then:

1. (A) deadlock is impossible
2. (B) the RAG is wrong
3. (C) deadlock is certain
4. (D) deadlock is possible but not certain

**Q4**MCQ1 markStarvation

A low-priority process never gets the CPU because higher-priority processes keep arriving. This is:

1. (A) a race condition
2. (B) circular wait
3. (C) starvation
4. (D) deadlock

**Q5**NAT1 markNeed

Max (7, 5, 3), Allocation (0, 1, 0). Need of resource B?

Numerical answer: \_\_\_\_\_\_\_\_

**Q6**NAT2 marksBanker's

13 units of one resource. A holds 6 (max 9), B holds 2 (max 5), C holds 2 (max 8). How many units are free after the first process of the safe sequence A, B, C finishes?

Numerical answer: \_\_\_\_\_\_\_\_

**Q7**MCQ2 marksBanker's

In the same state, B asks for 1 more unit. What happens?

1. (A) Granted: still safe
2. (B) B waits: unsafe
3. (C) B waits: not enough free units
4. (D) Error: exceeds B's maximum

**Q8**MCQ1 markUnsafe

Which is true?

1. (A) Safe and unsafe mean the same
2. (B) Every deadlocked state is unsafe
3. (C) Safe states can be deadlocked
4. (D) Every unsafe state is a deadlock

**Q9**MCQ1 markPrevention

Numbering resource types and requesting them only in increasing order breaks:

1. (A) circular wait
2. (B) no pre-emption
3. (C) mutual exclusion
4. (D) hold and wait

**Q10**NAT2 marksSafety

Worked example of Lesson 4.1.2 (Available (2,1,2)): after P3 and P1 finish, what is the total of the three Work values?

Numerical answer: \_\_\_\_\_\_\_\_

**Q11**NAT1 markMinimum resources

Processes need at most 2, 3, 4 and 5 units of one resource. Minimum units for which deadlock is impossible?

Numerical answer: \_\_\_\_\_\_\_\_

**Q12**NAT2 marksMaximum processes

A system has 16 units; each process needs at most 4. Largest number of processes that is guaranteed deadlock-free?

Numerical answer: \_\_\_\_\_\_\_\_

**Q13**NAT2 marksDetection

Lesson 4.1.3's detection example (no changes): in what position does P4 finish in the order the algorithm finds (scanning from P0 each pass)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q14**MCQ1 markRecovery

When recovering by pre-emption, what must the OS avoid?

1. (A) Choosing a victim
2. (B) Re-running detection
3. (C) Always picking the same process as the victim
4. (D) Rolling back the victim

**Q15**MCQ1 markStrategy

Most general-purpose operating systems handle deadlock by:

1. (A) wait-for graphs on every request
2. (B) ignoring it (ostrich approach)
3. (C) the banker's algorithm
4. (D) requesting all resources at start

### ✓Answer Vault

🔐 Open the Answer Vault

**Q1** Answer: (B) (C) (D)2 marks

Breaking any of the four conditions works.

- **(A) is wrong:** Not a deadlock condition.

Re-read: [Lesson 4.1.1](#l-4-1-1) — Deadlock: the four conditions and resource-allocation graphs

**Q2** Answer: (C)1 mark

Request edge.

- **(A) is wrong:** Free instances have no edge.
- **(B) is wrong:** No edge then.
- **(D) is wrong:** That is R → P.

Re-read: [Lesson 4.1.1](#l-4-1-1) — Deadlock: the four conditions and resource-allocation graphs

**Q3** Answer: (D)2 marks

Another holder may finish and release.

- **(A) is wrong:** It may still be deadlocked.
- **(B) is wrong:** Such graphs are valid.
- **(C) is wrong:** Only with single instances.

Re-read: [Lesson 4.1.1](#l-4-1-1) — Deadlock: the four conditions and resource-allocation graphs

**Q4** Answer: (C)1 mark

It waits indefinitely while others run.

- **(A) is wrong:** Not about shared data.
- **(B) is wrong:** No cycle.
- **(D) is wrong:** Others are not waiting for it.

Re-read: [Lesson 4.1.1](#l-4-1-1) — Deadlock: the four conditions and resource-allocation graphs

**Q5** Answer: 41 mark

5 − 1.

Re-read: [Lesson 4.1.2](#l-4-1-2) — Prevention and avoidance: safe states and the banker's algorithm

**Q6** Answer: 92 marks

Free 3; A takes 3 more, then returns all 9.

Re-read: [Lesson 4.1.2](#l-4-1-2) — Prevention and avoidance: safe states and the banker's algorithm

**Q7** Answer: (A)2 marks

Free 2; B's need 2 fits; B, then A, then C finish.

- **(B) is wrong:** A safe sequence exists.
- **(C) is wrong:** 1 ≤ 3.
- **(D) is wrong:** 3 ≤ 5.

Re-read: [Lesson 4.1.2](#l-4-1-2) — Prevention and avoidance: safe states and the banker's algorithm

**Q8** Answer: (B)1 mark

A deadlock leaves no way for those processes to finish.

- **(A) is wrong:** No.
- **(C) is wrong:** Safe means a finishing order exists.
- **(D) is wrong:** Unsafe only risks deadlock.

Re-read: [Lesson 4.1.2](#l-4-1-2) — Prevention and avoidance: safe states and the banker's algorithm

**Q9** Answer: (A)1 mark

No cycle can form.

- **(B) is wrong:** Nothing is taken away.
- **(C) is wrong:** Still exclusive.
- **(D) is wrong:** Processes still hold and wait.

Re-read: [Lesson 4.1.2](#l-4-1-2) — Prevention and avoidance: safe states and the banker's algorithm

**Q10** Answer: 102 marks

Work (4, 2, 4).

Re-read: [Lesson 4.1.2](#l-4-1-2) — Prevention and avoidance: safe states and the banker's algorithm

**Q11** Answer: 111 mark

1 + 2 + 3 + 4 + 1.

Re-read: [Lesson 4.1.3](#l-4-1-3) — Detection, recovery, and the minimum-resources formula

**Q12** Answer: 52 marks

3n + 1 ≤ 16.

Re-read: [Lesson 4.1.3](#l-4-1-3) — Detection, recovery, and the minimum-resources formula

**Q13** Answer: 52 marks

P3, then P0, P1, P2, P4.

Re-read: [Lesson 4.1.3](#l-4-1-3) — Detection, recovery, and the minimum-resources formula

**Q14** Answer: (C)1 mark

That process would starve.

- **(A) is wrong:** A victim is needed.
- **(B) is wrong:** Running detection again is fine.
- **(D) is wrong:** Rollback is part of the method.

Re-read: [Lesson 4.1.3](#l-4-1-3) — Detection, recovery, and the minimum-resources formula

**Q15** Answer: (B)1 mark

Deadlocks are rare and checks are costly.

- **(A) is wrong:** Too costly.
- **(C) is wrong:** Too costly and needs maxima.
- **(D) is wrong:** Wastes resources.

Re-read: [Lesson 4.1.3](#l-4-1-3) — Detection, recovery, and the minimum-resources formula

Type next → [**5.1.1** Addresses and contiguous allocation: fits and fragmentation](#l-5-1-1)

# 🧠Phase 5 — Memory Management & Virtual Memory

## 📄Lesson 5.1.1 — Addresses and contiguous allocation: fits and fragmentation

Phase 5 › Memory Management & Virtual Memory › Chapter 5.1 Contiguous allocation › Topic 5.1.1

Phase 5Ch 5.1 Contiguous allocationTopic 5.1.1GATE weight: Medium≈ 45 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. How many units make deadlock impossible for needs k₁ … kₙ? from [Lesson 4.1.3](#l-4-1-3)
2. Name the four parts of a process in memory. from [Lesson 1.1.1](#l-1-1-1)
3. How many address bits are needed for 64 KB of byte-addressable memory? from [Lesson 0.1.1](#l-0-1-1)

### 1The Hook

🎣

A car park has spaces of different lengths left between parked cars. A new car arrives: do you take the first space it fits in, the tightest one, or the biggest one? After a while, the car park is full of small useless gaps even though, added up, there is room for a bus. That is memory allocation, and those useless gaps are **fragmentation**. GATE asks you to place a list of requests by first, best and worst fit and to spot which one fails.

### 2Predict First

🤔

Free memory holes, in order: 150, 350, 200, 500, 100 KB. A 180 KB program arrives. Which hole does "take the first one that is big enough" choose?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

The **350 KB** hole (150 is too small, 350 is the first that fits).

🗣️

In plain words

A program uses addresses starting from 0 as if it had memory to itself (**logical addresses**). The hardware adds where the program really sits in RAM to get the **physical address**. In the simplest scheme each process gets one unbroken block of RAM, and the OS must choose which free gap ("hole") to put it in.

#### 1. Logical vs physical addresses

- **Logical (virtual) address**: generated by the CPU while running the program.
- **Physical address**: the actual location in RAM.
- The **MMU** (memory-management unit) hardware translates every logical address on the fly.

#### 2. Base (relocation) and limit registers

The OS loads two registers when it dispatches a process:

- **limit** = size of the process's block; **base** = where the block starts.
- For each logical address L: if L \< limit, physical = **base + L**; otherwise **trap** (addressing error), so a process can't touch others' memory.

Example: base 3000, limit 1200. L = 500 → 3500. L = 1300 → trap.

#### 3. Contiguous allocation

- **Fixed partitions**: memory is cut into blocks in advance; a process gets a whole block. Unused space **inside** a block is **internal fragmentation**.
- **Variable partitions**: each process gets exactly what it asks for; free memory becomes scattered **holes**. Enough total free space that is not in one piece is **external fragmentation**.
- **Compaction**: slide processes together to merge holes (costly; needs relocation at run time).
- With first fit, statistics show that for N allocated blocks about 0.5N more are lost to fragmentation (the **50% rule**): up to one third of memory may be unusable.

#### 4. Placement strategies (variable partitions)

| Strategy | Chooses | Notes |
| --- | --- | --- |
| **First fit** | the first hole big enough | fast |
| **Next fit** | like first fit, but starts searching where the last search stopped | spreads allocations |
| **Best fit** | the smallest hole big enough | leaves tiny leftover holes |
| **Worst fit** | the largest hole | leaves big leftover holes |

#### 5. Worked example

Holes (in memory order): 150, 350, 200, 500, 100 KB. Requests, in order: 180, 90, 320, 240 KB.

| Request | First fit | Best fit | Worst fit |
| --- | --- | --- | --- |
| 180 | 350 → 170 left | 200 → 20 left | 500 → 320 left |
| 90 | 150 → 60 left | 100 → 10 left | 350 → 260 left |
| 320 | 500 → 180 left | 350 → 30 left | 320 → 0 left |
| 240 | **fails** (largest hole 200) | 500 → 260 left | 260 → 20 left |

Here first fit (and next fit) fail, while best and worst fit place everything. No strategy is always best.

### 4Visual

```
Base and limit check

 CPU --L--> [ L < limit ? ] --yes--> [ + base ] --> physical address --> RAM
                  |
                  no
                  v
           trap: addressing error

 base 3000, limit 1200:   L = 500  -> 3500      L = 1300 -> trap
```

### 5Worked Examples

Example 1 Easy

Base 4000, limit 600. Translate logical addresses 250 and 600.

Solution

250 \< 600 → **4250**. 600 is not \< 600 → **trap**.

Example 2 Medium

Memory has fixed partitions of 200 KB. Processes of 120, 180 and 50 KB are loaded, one per partition. Total internal fragmentation?

Solution

(200 − 120) + (200 − 180) + (200 − 50) = 80 + 20 + 150 = **250 KB**.

Example 3 GATE

In the worked example, with best fit, how much free memory is left in the 500 KB hole at the end?

Solution

Only the last request (240) uses it: **260 KB**.

### 6GATE Traps

⚠️

- The limit check is L \< limit (logical address), done **before** adding the base.
- Internal fragmentation: waste inside an allocated block. External: free memory split into pieces.
- First fit is not "smallest" and best fit is not "first"; read which hole each picks.
- Next fit continues from the last allocation, not from the start.

### 7Memory Hook

🧠

**"First = earliest, Best = tightest, Worst = biggest. Inside waste = internal, gaps between = external."**

### 8Connect the Dots

External fragmentation comes from needing **one unbroken block** per process. The next lesson removes that need: **paging** cuts both the program and memory into equal small pieces, so any free piece can be used.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**NAT1 markRelocation

Base register 2500, limit register 800. A process issues logical address 640. Physical address?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**MCQ1 markLimit

Base 2500, limit 800. Logical address 800 is issued. What happens?

1. (A) The limit is increased
2. (B) Physical address 800
3. (C) Physical address 3300
4. (D) Trap: addressing error

**Q3**NAT2 marksBest fit

Holes 150, 350, 200, 500, 100 KB; requests 180, 90, 320, 240 KB placed by best fit. Total size of the leftover pieces of the holes that were used?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**MCQ2 marksFirst fit

Same holes and requests with first fit. Which request cannot be placed?

1. (A) 90
2. (B) 240
3. (C) 320
4. (D) 180

**Q5**MCQ1 markFragmentation

Fixed-size partitions mainly cause:

1. (A) no fragmentation
2. (B) external fragmentation
3. (C) thrashing
4. (D) internal fragmentation

### 10Rule Card

- Logical address from the CPU; MMU makes the physical address.
- Base/limit: if L \< limit then physical = base + L, else trap.
- Fixed partitions → internal fragmentation; variable → external; compaction merges holes.
- First fit (first big enough), next fit (continue from last), best fit (smallest big enough), worst fit (largest).
- 50% rule: N blocks allocated → about 0.5N lost (one third).

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

logical addressphysical addressMMUbase (relocation) registerlimit registercontiguous allocationfixed partitionsvariable partitionsholesinternal fragmentationexternal fragmentationcompactionfirst fitnext fitbest fitworst fit50% rule

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. Σ(kᵢ − 1) + 1.
2. Code (text), data, heap, stack.
3. 16.

#### Self-Test

**Q1** Answer: 31401 mark

640 \< 800, so 2500 + 640.

Re-read: [Lesson 5.1.1](#l-5-1-1) — Addresses and contiguous allocation: fits and fragmentation

**Q2** Answer: (D)1 mark

The valid logical addresses are 0 to 799.

- **(A) is wrong:** Registers aren't changed by an access.
- **(B) is wrong:** Base is always added for valid addresses.
- **(C) is wrong:** 800 is not below the limit.

Re-read: [Lesson 5.1.1](#l-5-1-1) — Addresses and contiguous allocation: fits and fragmentation

**Q3** Answer: 3202 marks

20 + 10 + 30 + 260.

Re-read: [Lesson 5.1.1](#l-5-1-1) — Addresses and contiguous allocation: fits and fragmentation

**Q4** Answer: (B)2 marks

Leftover holes are 60, 170, 200, 180, 100.

- **(A) is wrong:** Goes into 150.
- **(C) is wrong:** Goes into 500.
- **(D) is wrong:** Goes into 350.

Re-read: [Lesson 5.1.1](#l-5-1-1) — Addresses and contiguous allocation: fits and fragmentation

**Q5** Answer: (D)1 mark

Unused space inside each partition.

- **(A) is wrong:** There is waste.
- **(B) is wrong:** Typical of variable partitions.
- **(C) is wrong:** Unrelated.

Re-read: [Lesson 5.1.1](#l-5-1-1) — Addresses and contiguous allocation: fits and fragmentation

Type next → [**5.2.1** Paging: pages, frames, page tables and the address split](#l-5-2-1)

## 📄Lesson 5.2.1 — Paging: pages, frames, page tables and the address split

Phase 5 › Memory Management & Virtual Memory › Chapter 5.2 Paging › Topic 5.2.1

Phase 5Ch 5.2 PagingTopic 5.2.1GATE weight: High≈ 55 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. What is external fragmentation? from [Lesson 5.1.1](#l-5-1-1)
2. With base 3000 and limit 1200, where does logical address 500 go? from [Lesson 5.1.1](#l-5-1-1)
3. How many bits address 2³² bytes? from [Lesson 0.1.1](#l-0-1-1)

### 1The Hook

🎣

A long book doesn't need one shelf long enough for the whole thing: tear it into 10-page booklets, put each booklet in **any** free slot, and keep an index card saying which slot holds which booklet. **Paging** does exactly that with programs. GATE asks for the address split (page number and offset bits) and the size of the page table in almost every paper.

### 2Predict First

🤔

Pages are 1 KB (1024 bytes). The CPU issues logical address 3000. Which page is it on, and how far into that page?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

3000 = 2 × 1024 + 952 → **page 2, offset 952**.

🗣️

In plain words

Cut the program into equal pieces called **pages** and RAM into pieces of the same size called **frames**. Any page can go in any free frame. A **page table** (one per process) records which frame holds each page. An address is split into "which page" and "where inside the page"; only the page part is translated.

#### 1. Pages, frames, page table

- Page size = frame size = a power of 2 (e.g. 4 KB).
- **Page table**: entry p holds the **frame number** of page p (plus some bits, below).
- No external fragmentation: every free frame is usable. Only the last page of a process may be partly empty (**internal fragmentation**, on average half a page).

#### 2. Splitting an address

If the page size is 2ᵈ bytes and logical addresses have m bits:

- **offset** = the low **d** bits; **page number** = the high **m − d** bits.
- Number of pages = 2ᵐ⁻ᵈ.

Translation: frame f = PageTable\[p\]; **physical address = f × page size + offset**. Example: 1 KB pages, logical 3000 → p = 2, d = 952. If page 2 is in frame 5: 5 × 1024 + 952 = **6072**.

#### 3. Page-table size

**Page-table size = number of pages × size of one entry (PTE).**

- 32-bit logical addresses, 4 KB pages (12-bit offset): 2²⁰ pages. With 4-byte entries: 2²⁰ × 4 B = **4 MB** per process.
- Frame-number bits = physical-address bits − offset bits. With 1 GB of RAM (30 bits) and 4 KB frames: 30 − 12 = **18** bits; the rest of the entry holds flag bits.

#### 4. What else is in a page-table entry

- **Valid/invalid bit**: is this page part of the process? An access to an invalid page traps to the OS.
- **Protection bits**: read / write / execute.
- **Modified (dirty) bit** and **referenced bit** (used in Chapter 5.3).
- The OS keeps the table's start address in a register (the **page-table base register**) and reloads it on each context switch.

#### 5. Sharing

Read-only code (e.g. a text editor used by 40 users) can be shared: each process's page table points to the **same frames**.

### 4Visual

```
Logical address (m bits)                          Physical address
+--------------+----------+                      +--------------+----------+
| page p       | offset d |   --> page table --> | frame f      | offset d |
| (m - d bits) | (d bits) |       p -> f         |              | (copied) |
+--------------+----------+                      +--------------+----------+

1 KB pages, address 3000:  p = 3000 div 1024 = 2,  d = 3000 mod 1024 = 952
page 2 -> frame 5:         physical = 5 x 1024 + 952 = 6072
```

### 5Worked Examples

Example 1 Easy

16-bit logical addresses, 1 KB pages. How many bits are page number and offset? How many pages?

Solution

Offset 10 bits; page number **6** bits; 2⁶ = **64** pages.

Example 2 Medium

A process needs 10,000 bytes and pages are 4 KB (4096 bytes). How many frames does it get, and how much internal fragmentation is there?

Solution

10,000 / 4096 → **3** frames (12,288 bytes); waste 12,288 − 10,000 = **2,288 bytes**.

Example 3 GATE

Logical address 32 bits, page size 8 KB, page-table entry 4 bytes. Size of the page table?

Solution

Offset 13 bits → 2¹⁹ pages × 4 B = 2²¹ B = **2 MB**.

### 6GATE Traps

⚠️

- Offset bits come from the **page size**, not from memory size.
- Page-table entries = number of **pages** (logical side), not number of frames.
- Frame-number width depends on **physical** memory size.
- Paging has internal fragmentation (last page), not external.

### 7Memory Hook

🧠

**"Low bits ride along (offset); high bits get looked up (page → frame)."**

### 8Connect the Dots

Each memory access now needs **two** memory accesses: one to read the page table, one for the data. That doubles memory time. The next lesson fixes it with a small fast cache (the **TLB**) and shrinks huge page tables with **multilevel paging**.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**NAT1 markAddress split

Logical addresses are 32 bits and pages are 4 KB. How many bits form the page number?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT1 markTranslation

Pages are 1 KB. Logical address 5000 is on page 4. Page 4 is in frame 9. Physical address?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT2 marksPage-table size

Logical addresses are 32 bits, pages 4 KB, page-table entries 4 bytes. Page-table size in MB?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**NAT2 marksFrame bits

Physical memory is 1 GB and frames are 4 KB. Minimum number of bits for a frame number?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**MCQ1 markFragmentation

Paging suffers from:

1. (A) internal fragmentation only (in the last page)
2. (B) external fragmentation only
3. (C) both kinds equally
4. (D) neither

### 10Rule Card

- Page = frame size = 2ᵈ; offset = low d bits; page number = high m − d bits.
- Physical = frame × page size + offset.
- Page-table size = (#pages) × (PTE size); frame bits = physical bits − d.
- PTE: frame, valid, protection, dirty, referenced. Shared code → same frames.
- Paging: internal fragmentation only (≈ half a page per process).

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

pageframepage tablepage number and offsetaddress translationpage-table sizepage-table entryframe-number bitsvalid/invalid bitprotection bitspage-table base registershared pages

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. Enough free memory in total, but not in one piece.
2. 3500.
3. 32.

#### Self-Test

**Q1** Answer: 201 mark

32 − 12.

Re-read: [Lesson 5.2.1](#l-5-2-1) — Paging: pages, frames, page tables and the address split

**Q2** Answer: 101201 mark

Offset 5000 − 4096 = 904; 9 × 1024 + 904.

Re-read: [Lesson 5.2.1](#l-5-2-1) — Paging: pages, frames, page tables and the address split

**Q3** Answer: 42 marks

2²⁰ entries × 4 B.

Re-read: [Lesson 5.2.1](#l-5-2-1) — Paging: pages, frames, page tables and the address split

**Q4** Answer: 182 marks

2³⁰ / 2¹² frames.

Re-read: [Lesson 5.2.1](#l-5-2-1) — Paging: pages, frames, page tables and the address split

**Q5** Answer: (A)1 mark

Every frame can be used; only the last page may be part-empty.

- **(B) is wrong:** Any free frame fits any page.
- **(C) is wrong:** No external fragmentation.
- **(D) is wrong:** The last page wastes space.

Re-read: [Lesson 5.2.1](#l-5-2-1) — Paging: pages, frames, page tables and the address split

Type next → [**5.2.2** TLBs, effective access time and multilevel page tables](#l-5-2-2)

## 📄Lesson 5.2.2 — TLBs, effective access time and multilevel page tables

Phase 5 › Memory Management & Virtual Memory › Chapter 5.2 Paging › Topic 5.2.2

Phase 5Ch 5.2 PagingTopic 5.2.2GATE weight: High≈ 55 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. Page-table size = ? from [Lesson 5.2.1](#l-5-2-1)
2. Physical address from frame f and offset d? from [Lesson 5.2.1](#l-5-2-1)
3. What does a context switch save and load? from [Lesson 1.1.2](#l-1-1-2)

### 1The Hook

🎣

A librarian who checks the index card for every single book fetch is slow; one who remembers the last few cards is fast. The **TLB** is that memory: a tiny, very fast cache of recent page→frame translations. GATE's favourite memory numerical, "effective memory access time", is built on it. And when page tables grow to many megabytes, we page the page table itself: **multilevel paging**.

### 2Predict First

🤔

Memory access takes 100 ns. With paging and no cache, how long does one useful memory access take?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

**200 ns**: 100 ns to read the page-table entry, then 100 ns for the data itself.

🗣️

In plain words

The TLB is a small hardware table of recent (page → frame) pairs, searched all at once. If the page is there (a **hit**), translation is almost free. If not (a **miss**), read the page table in memory and remember the pair in the TLB. Multilevel paging splits the page number into parts, each indexing a smaller table, so tables for unused regions need not exist.

#### 1. Effective access time with a TLB

Let t = TLB lookup time, m = memory access time, h = hit ratio.

- Hit: t + m. Miss: t + m (page table) + m (data) = t + 2m.
- **EAT = h(t + m) + (1 − h)(t + 2m)**.

Example: m = 100 ns, t = 20 ns, h = 0.8 → 0.8 × 120 + 0.2 × 220 = **140 ns**. With h = 0.98: **122 ns**. If the question says TLB time is negligible, put t = 0.

#### 2. TLB facts

- Typically 32–1024 entries, searched in parallel (associative memory).
- On a context switch the TLB must be flushed, unless entries carry an **address-space identifier (ASID)**.
- Higher hit ratio → EAT close to a single memory access.

#### 3. Multilevel (hierarchical) paging

Problem: a 4 MB page table per process, mostly unused. Solution: split the page number. Two-level example (32-bit addresses, 4 KB pages, 4-byte entries):

- One page holds 4096 / 4 = **1024 entries** → 10 bits index each level.
- Address = **p1 (10) | p2 (10) | offset (12)**. p1 indexes the outer table; that entry gives the inner table; p2 indexes it.
- Only inner tables for used regions are created.

General rule: entries per page = page size / PTE size; bits per level = log₂ of that; **levels = ⌈(logical bits − offset bits) / bits per level⌉**. Example: 48-bit addresses, 4 KB pages, 8-byte entries → 512 entries per page → 9 bits per level → 36 / 9 = **4 levels**.

#### 4. EAT with k levels

A TLB miss needs k page-table reads plus the data: t + (k + 1)m. Example: 4 levels, m = 100, t = 10, h = 0.95 → 0.95 × 110 + 0.05 × 510 = **130 ns**.

#### 5. Other page-table designs

- **Inverted page table**: one entry per **frame** (not per page), holding (process id, page). One table for the whole system; small, but finding a page means searching, so it is combined with a **hash table**.
- **Hashed page table**: hash the page number into a bucket of (page, frame) pairs; good for 64-bit addresses.

### 4Visual

```
Two-level paging, 32-bit address, 4 KB pages

+---------+---------+------------+
| p1 (10) | p2 (10) | offset(12) |
+---------+---------+------------+
     |          |
     v          v
 outer table -> inner table -> frame f  ->  physical = f x 4096 + offset
 (1024 entries)  (1024 entries)

TLB hit : t + m        TLB miss: t + 2m (one level)   t + (k+1)m (k levels)
```

### 5Worked Examples

Example 1 Easy

m = 100 ns, TLB time negligible, hit ratio 0.9. EAT?

Solution

0.9 × 100 + 0.1 × 200 = **110 ns**.

Example 2 Medium

32-bit addresses, 4 KB pages, 4-byte entries, two-level paging with each table one page. How large is the outer page table?

Solution

1024 entries × 4 B = **4 KB** (exactly one page).

Example 3 GATE

46-bit virtual addresses, 8 KB pages, 4-byte entries, every page table must fit in one page. How many levels?

Solution

8 KB / 4 B = 2048 entries → 11 bits per level. 46 − 13 = 33 bits → 33 / 11 = **3 levels**.

### 6GATE Traps

⚠️

- A TLB miss costs t + 2m (one level), not just 2m, when t is given.
- Levels: divide the **page-number bits** (not all address bits) by bits per level, and round **up**.
- Inverted page table size depends on **physical** memory (one entry per frame).
- Flushing the TLB on a context switch is avoided with ASIDs.

### 7Memory Hook

🧠

**"Hit: t + m. Miss: t + (levels + 1)m. Levels = ⌈page bits / log₂(page size / PTE)⌉."**

### 8Connect the Dots

Paging cuts programs into equal pieces that mean nothing to the programmer. The next lesson looks at **segmentation**, which divides a program into meaningful parts (code, data, stack), and at combining the two.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**NAT2 marksEAT

Memory access 100 ns, TLB lookup 20 ns, hit ratio 0.8 (single-level paging). Effective access time in ns?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT2 marksEAT

Memory access 50 ns, TLB lookup 10 ns, hit ratio 0.9 (single-level paging). Effective access time in ns?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT2 marksLevels

48-bit virtual addresses, 4 KB pages, 8-byte page-table entries; each table fits in one page. Number of levels?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**NAT2 marksMultilevel EAT

4-level paging, memory access 100 ns, TLB 10 ns, hit ratio 0.95. EAT in ns?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**MCQ1 markInverted page table

An inverted page table has one entry per:

1. (A) process
2. (B) TLB entry
3. (C) physical frame
4. (D) page of each process

### 10Rule Card

- EAT = h(t + m) + (1 − h)(t + 2m); with k levels the miss costs t + (k + 1)m.
- TLB: small associative cache; flush on switch unless ASIDs.
- Multilevel: entries per page = page size / PTE; bits per level = log₂ of it; levels = ⌈(m − d) / bits per level⌉.
- Inverted table: one entry per frame, searched via hashing.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

translation lookaside bufferTLB hit and misshit ratioeffective access timeASIDmultilevel pagingouter and inner page tablesnumber of levelsinverted page tablehashed page table

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. Number of pages × entry size.
2. f × page size + d.
3. The CPU state (registers, PC) in the PCB.

#### Self-Test

**Q1** Answer: 1402 marks

0.8 × 120 + 0.2 × 220.

Re-read: [Lesson 5.2.2](#l-5-2-2) — TLBs, effective access time and multilevel page tables

**Q2** Answer: 652 marks

0.9 × 60 + 0.1 × 110.

Re-read: [Lesson 5.2.2](#l-5-2-2) — TLBs, effective access time and multilevel page tables

**Q3** Answer: 42 marks

9 bits per level; 36 / 9.

Re-read: [Lesson 5.2.2](#l-5-2-2) — TLBs, effective access time and multilevel page tables

**Q4** Answer: 1302 marks

0.95 × 110 + 0.05 × 510.

Re-read: [Lesson 5.2.2](#l-5-2-2) — TLBs, effective access time and multilevel page tables

**Q5** Answer: (C)1 mark

Its size depends on physical memory.

- **(A) is wrong:** No.
- **(B) is wrong:** No.
- **(D) is wrong:** That is the ordinary page table.

Re-read: [Lesson 5.2.2](#l-5-2-2) — TLBs, effective access time and multilevel page tables

Type next → [**5.2.3** Segmentation, and segmentation with paging](#l-5-2-3)

## 📄Lesson 5.2.3 — Segmentation, and segmentation with paging

Phase 5 › Memory Management & Virtual Memory › Chapter 5.2 Paging › Topic 5.2.3

Phase 5Ch 5.2 PagingTopic 5.2.3GATE weight: Medium≈ 40 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. EAT with a TLB (one level)? from [Lesson 5.2.2](#l-5-2-2)
2. Which kind of fragmentation does paging have? from [Lesson 5.2.1](#l-5-2-1)
3. What check does the limit register perform? from [Lesson 5.1.1](#l-5-1-1)

### 1The Hook

🎣

A programmer thinks of a program as parts: "the main code", "the array", "the stack", not as "page 17". **Segmentation** divides memory the way programmers think: each part is a **segment** with its own size. GATE asks you to translate (segment, offset) pairs and to say which ones trap.

### 2Predict First

🤔

Segment 1 starts at physical address 5000 and is 300 bytes long. Where does (segment 1, offset 120) go? What about (segment 1, offset 350)?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

(1, 120) → **5120**. (1, 350): 350 ≥ 300 → **trap**.

🗣️

In plain words

Each segment is like a small base-and-limit block of its own. A logical address names a segment and an offset inside it. The **segment table** stores each segment's start (base) and length (limit). The offset must be smaller than the limit.

#### 1. Segmentation

- Logical address = **(segment number s, offset d)**.
- Segment table entry s = **(base, limit)**.
- If d \< limit: physical = **base + d**; otherwise **trap**.

Example segment table:

| Segment | Base | Limit |
| --- | --- | --- |
| 0 | 2000 | 600 |
| 1 | 5000 | 300 |
| 2 | 1200 | 500 |
| 3 | 3500 | 900 |

- (0, 450) → 2450. (1, 350) → trap. (2, 100) → 1300. (3, 899) → 4399.

#### 2. Paging vs segmentation

|  | Paging | Segmentation |
| --- | --- | --- |
| Pieces | equal size, invisible to the programmer | variable size, logical units |
| Fragmentation | internal | external |
| Address | (page, offset) found by splitting bits | (segment, offset) given separately |
| Protection/sharing | per page | natural per segment (e.g. share code, protect data) |

#### 3. Segmentation with paging

Each segment is itself paged: logical address = **(s, p, d)**. The segment table entry points to that segment's page table; the limit check uses the segment length. This keeps the logical view of segments and the no-external-fragmentation benefit of paging (used by Intel x86 in 32-bit mode).

### 4Visual

```
(s, d) --> segment table[s] = (base, limit)
             |
             +-- d < limit ?  yes --> physical = base + d
                              no  --> trap

Table: seg 0 (2000, 600)  seg 1 (5000, 300)  seg 2 (1200, 500)  seg 3 (3500, 900)
(0,450) -> 2450   (1,350) -> trap   (2,100) -> 1300   (3,899) -> 4399
```

### 5Worked Examples

Example 1 Easy

Using the table above, translate (3, 100).

Solution

100 \< 900 → 3500 + 100 = **3600**.

Example 2 Medium

Using the table above, which of (0, 600), (2, 499), (1, 0) trap?

Solution

Only **(0, 600)**: 600 is not \< 600. (2, 499) → 1699; (1, 0) → 5000.

Example 3 GATE

A system uses segmentation with paging. A segment is 9 KB and pages are 4 KB. How many frames does the segment occupy, and how much is wasted inside them?

Solution

⌈9 / 4⌉ = **3** frames; 12 − 9 = **3 KB** of internal fragmentation.

### 6GATE Traps

⚠️

- The offset check is d \< limit (strictly less).
- Segmentation has **external** fragmentation (variable sizes), paging internal.
- In segmentation the segment number is not taken from "high bits of a flat address"; it is a separate part of the address.
- With segmentation + paging, the final waste is internal (last page of each segment).

### 7Memory Hook

🧠

**"Segment = base + limit per part. Offset under limit, or trap."**

### 8Connect the Dots

Chapters 5.1 and 5.2 are complete: we can place, translate and protect a program that sits fully in memory. Chapter 5.3 removes the last requirement: with **virtual memory** only the pages actually in use need to be in RAM.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**NAT1 markTranslation

Segment 2 has base 1200 and limit 500. Physical address of (2, 340)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**MCQ1 markTrap

Segment 0 has base 2000 and limit 600. Logical address (0, 600) gives:

1. (A) 2000
2. (B) 600
3. (C) 2600
4. (D) a trap

**Q3**MCQ1 markFragmentation

Pure segmentation suffers from:

1. (A) no fragmentation
2. (B) external fragmentation
3. (C) internal fragmentation
4. (D) Belady's anomaly

**Q4**NAT2 marksTranslation

Segment table: segment 3 has base 3500, limit 900. Physical address of (3, 899)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**MCQ1 markSegmentation with paging

In segmentation with paging, a logical address consists of:

1. (A) (segment, offset) translated by base + offset only
2. (B) (page, offset)
3. (C) (segment, page, offset)
4. (D) (frame, offset)

### 10Rule Card

- Segment table entry (base, limit); (s, d) → base + d if d \< limit, else trap.
- Paging: equal pieces, internal fragmentation. Segmentation: logical pieces, external fragmentation, natural sharing/protection.
- Segmentation with paging: (s, p, d); each segment paged.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

segmentsegment number and offsetsegment tablesegment base and limitsegmentation trappaging vs segmentationsegmentation with paging

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. h(t + m) + (1 − h)(t + 2m).
2. Internal (last page).
3. Logical address \< limit, else trap.

#### Self-Test

**Q1** Answer: 15401 mark

340 \< 500.

Re-read: [Lesson 5.2.3](#l-5-2-3) — Segmentation, and segmentation with paging

**Q2** Answer: (D)1 mark

600 is not less than 600.

- **(A) is wrong:** That is offset 0.
- **(B) is wrong:** Base must be added.
- **(C) is wrong:** Beyond the segment.

Re-read: [Lesson 5.2.3](#l-5-2-3) — Segmentation, and segmentation with paging

**Q3** Answer: (B)1 mark

Segments have different sizes, leaving holes.

- **(A) is wrong:** Holes appear.
- **(C) is wrong:** Each segment gets exactly its size.
- **(D) is wrong:** That is about page replacement.

Re-read: [Lesson 5.2.3](#l-5-2-3) — Segmentation, and segmentation with paging

**Q4** Answer: 43992 marks

899 \< 900.

Re-read: [Lesson 5.2.3](#l-5-2-3) — Segmentation, and segmentation with paging

**Q5** Answer: (C)1 mark

Each segment has its own page table.

- **(A) is wrong:** Pure segmentation.
- **(B) is wrong:** Pure paging.
- **(D) is wrong:** That is physical.

Re-read: [Lesson 5.2.3](#l-5-2-3) — Segmentation, and segmentation with paging

Type next → [**LI-5.1-5.2** Chapters 5.1–5.2 Lock-in](#l-LI-5-1-5-2)

## 🔒Chapters 5.1–5.2 Lock-in — Contiguous allocation & Paging

Phase 5 › Memory Management & Virtual Memory › Chapter 5.1 Contiguous allocation › Chapter 5.2 Paging

Phase 5Ch 5.1 Contiguous allocationCh 5.2 Paging

### ACompressed recap

🧾

Base/limit: L \< limit → base + L. Fixed partitions → internal, variable → external fragmentation; first/next/best/worst fit. Paging: offset = log₂(page size) bits, page number = the rest; physical = f × size + d; page table = #pages × PTE; frame bits = physical bits − offset bits. TLB EAT = h(t + m) + (1 − h)(t + 2m); multilevel: levels = ⌈page bits / log₂(page size / PTE)⌉, miss = t + (k + 1)m; inverted table per frame. Segmentation: (s, d), base + d if d \< limit; external fragmentation.

### BMerged rule card

[5.1.1](#l-5-1-1) Addresses and contiguous allocation: fits and fragmentation

- Logical address from the CPU; MMU makes the physical address.
- Base/limit: if L \< limit then physical = base + L, else trap.
- Fixed partitions → internal fragmentation; variable → external; compaction merges holes.
- First fit (first big enough), next fit (continue from last), best fit (smallest big enough), worst fit (largest).
- 50% rule: N blocks allocated → about 0.5N lost (one third).

[5.2.1](#l-5-2-1) Paging: pages, frames, page tables and the address split

- Page = frame size = 2ᵈ; offset = low d bits; page number = high m − d bits.
- Physical = frame × page size + offset.
- Page-table size = (#pages) × (PTE size); frame bits = physical bits − d.
- PTE: frame, valid, protection, dirty, referenced. Shared code → same frames.
- Paging: internal fragmentation only (≈ half a page per process).

[5.2.2](#l-5-2-2) TLBs, effective access time and multilevel page tables

- EAT = h(t + m) + (1 − h)(t + 2m); with k levels the miss costs t + (k + 1)m.
- TLB: small associative cache; flush on switch unless ASIDs.
- Multilevel: entries per page = page size / PTE; bits per level = log₂ of it; levels = ⌈(m − d) / bits per level⌉.
- Inverted table: one entry per frame, searched via hashing.

[5.2.3](#l-5-2-3) Segmentation, and segmentation with paging

- Segment table entry (base, limit); (s, d) → base + d if d \< limit, else trap.
- Paging: equal pieces, internal fragmentation. Segmentation: logical pieces, external fragmentation, natural sharing/protection.
- Segmentation with paging: (s, p, d); each segment paged.

### CInterleaved GATE-style questions

**Q1**NAT1 markBase/limit

Base 7000, limit 2500. Physical address of logical address 2499?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT2 marksWorst fit

Holes 150, 350, 200, 500, 100 KB; requests 180, 90, 320, 240 KB by worst fit. Size of the hole that the 240 KB request is placed in (its size just before placement)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT1 markPages

A 64 KB logical address space with 2 KB pages has how many pages?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**NAT2 marksTranslation

Pages are 2 KB. Logical address 9000 is on page p; page p is in frame 7. Physical address?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**NAT2 marksPage table

Logical addresses 34 bits, pages 16 KB, entries 4 bytes. Page-table size in MB?

Numerical answer: \_\_\_\_\_\_\_\_

**Q6**NAT1 markEAT

Memory 80 ns, TLB time negligible, hit ratio 0.75. EAT in ns?

Numerical answer: \_\_\_\_\_\_\_\_

**Q7**NAT2 marksLevels

39-bit virtual addresses, 4 KB pages, 8-byte entries, each table one page. Number of levels?

Numerical answer: \_\_\_\_\_\_\_\_

**Q8**MCQ1 markSegmentation

Which statement about segmentation is true?

1. (A) Translation is base + offset after the check offset \< limit
2. (B) It needs no table
3. (C) It has no fragmentation
4. (D) All segments have the same size

### DAnswer Vault

🔐 Open the Answer Vault

**Q1** Answer: 94991 mark

Just inside the limit.

Re-read: [Lesson 5.1.1](#l-5-1-1) — Addresses and contiguous allocation: fits and fragmentation

**Q2** Answer: 2602 marks

After 180 → 500 (320 left) and 90 → 350 (260 left), 320 takes the 320 piece; 260 is now the largest.

Re-read: [Lesson 5.1.1](#l-5-1-1) — Addresses and contiguous allocation: fits and fragmentation

**Q3** Answer: 321 mark

2¹⁶ / 2¹¹.

Re-read: [Lesson 5.2.1](#l-5-2-1) — Paging: pages, frames, page tables and the address split

**Q4** Answer: 151442 marks

p = 4, offset 9000 − 8192 = 808; 7 × 2048 + 808.

Re-read: [Lesson 5.2.1](#l-5-2-1) — Paging: pages, frames, page tables and the address split

**Q5** Answer: 42 marks

2²⁰ entries × 4 B.

Re-read: [Lesson 5.2.1](#l-5-2-1) — Paging: pages, frames, page tables and the address split

**Q6** Answer: 1001 mark

0.75 × 80 + 0.25 × 160.

Re-read: [Lesson 5.2.2](#l-5-2-2) — TLBs, effective access time and multilevel page tables

**Q7** Answer: 32 marks

27 page bits / 9 per level.

Re-read: [Lesson 5.2.2](#l-5-2-2) — TLBs, effective access time and multilevel page tables

**Q8** Answer: (A)1 mark

Per-segment base and limit.

- **(B) is wrong:** The segment table.
- **(C) is wrong:** External fragmentation.
- **(D) is wrong:** Sizes vary.

Re-read: [Lesson 5.2.3](#l-5-2-3) — Segmentation, and segmentation with paging

Type next → [**5.3.1** Demand paging, page faults and effective access time](#l-5-3-1)

## 📄Lesson 5.3.1 — Demand paging, page faults and effective access time

Phase 5 › Memory Management & Virtual Memory › Chapter 5.3 Virtual memory › Topic 5.3.1

Phase 5Ch 5.3 Virtual memoryTopic 5.3.1GATE weight: High≈ 50 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. What does the valid/invalid bit in a page-table entry tell? from [Lesson 5.2.1](#l-5-2-1)
2. What does a TLB miss cost in single-level paging? from [Lesson 5.2.2](#l-5-2-2)
3. What is the medium-term scheduler's job? from [Lesson 1.1.2](#l-1-1-2)

### 1The Hook

🎣

A 500-page textbook, but today you only need chapter 3. You don't carry the whole book; you photocopy pages as you need them. **Demand paging** loads a page only when the program first touches it. Programs can be larger than RAM, more programs fit at once, and they start faster. The price: an occasional very slow **page fault**, which GATE turns into an effective-access-time question.

### 2Predict First

🤔

Memory access takes 100 ns; fetching a missing page from disk takes 10 ms (10,000,000 ns). If 1 access in 1000 needs the disk, roughly how long is the average access?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

About 0.999 × 100 + 0.001 × 10,000,000 ≈ **10,100 ns**: about 100 times slower than memory. Page faults must be very rare.

🗣️

In plain words

**Virtual memory** lets a process use more memory than the RAM it actually has. Its pages live on disk, and only the ones in use are copied into frames. The page table's valid bit now means "this page is **in memory**". Touching a page that isn't in memory causes a **page fault**: the OS fetches it from disk, fixes the table, and runs the instruction again.

#### 1. Demand paging

- Load a page only when it is first referenced (a "lazy" pager). **Pure demand paging** starts a process with no pages at all.
- Valid bit = 1: page in memory. Valid bit = 0: not in memory (or not part of the process).

#### 2. What happens on a page fault

1. The access finds valid = 0 → **trap** to the OS.
2. The OS checks the reference: illegal → kill the process; legal but not in memory → continue.
3. Find a **free frame** (if none, choose a victim page to replace: Lesson 5.3.2).
4. Schedule a **disk read** of the page into the frame (the process waits; another runs).
5. When the read completes, **update the page table** (frame number, valid = 1).
6. **Restart the instruction** that caused the fault.

#### 3. Effective access time with page faults

p = page-fault rate (0 ≤ p ≤ 1), ma = memory access time, s = page-fault service time: **EAT = (1 − p) × ma + p × s**. Example: ma = 100 ns, s = 10 ms = 10⁷ ns, p = 10⁻⁵ → 0.99999 × 100 + 10⁻⁵ × 10⁷ ≈ **200 ns** (twice as slow as memory). To keep EAT ≤ 200 ns: 100 + p(10⁷ − 100) ≤ 200 → p ≤ about 10⁻⁵ (one fault per 100,000 accesses).

#### 4. The dirty bit

When a victim page must be replaced, it is written back to disk **only if it was modified** (dirty bit = 1). So the service time depends on the victim: Average s = (fraction dirty) × s_dirty + (fraction clean) × s_clean. Example: 8 ms if clean, 20 ms if dirty, 70% dirty → 0.3 × 8 + 0.7 × 20 = **16.4 ms**.

#### 5. Copy-on-write

After `fork()`, parent and child **share** the parent's pages, marked read-only. Only when one of them writes to a page is that page copied. This makes `fork()` fast, especially when the child calls `exec()` at once.

### 4Visual

The six steps of handling a page fault. Step 4 is slow (milliseconds), so the process waits while another runs.

### 5Worked Examples

Example 1 Easy

ma = 200 ns, s = 8 ms, p = 0.001. EAT?

Solution

0.999 × 200 + 0.001 × 8,000,000 = 199.8 + 8000 = **8199.8 ns** (≈ 8.2 µs).

Example 2 Medium

ma = 100 ns, s = 10 ms, and we want EAT ≤ 110 ns. Largest page-fault rate?

Solution

100 + p(10⁷ − 100) ≤ 110 → p ≤ 10 / 9,999,900 ≈ **1.0 × 10⁻⁶**.

Example 3 GATE

Service time 8 ms if the victim is clean, 20 ms if dirty; 70% of victims are dirty; ma = 100 ns. Largest p with EAT ≤ 200 ns?

Solution

s = 16.4 ms = 16,400,000 ns. 100 + p(16,400,000 − 100) ≤ 200 → p ≤ 100 / 16,399,900 ≈ **6.1 × 10⁻⁶**.

### 6GATE Traps

⚠️

- Convert units: ms = 10⁶ ns.
- EAT formula weights the **fault** case with s (which already includes everything slow).
- A dirty victim adds a disk **write** before the read.
- An access to an illegal address is not served; the process is terminated.

### 7Memory Hook

🧠

**"EAT = (1 − p)·ma + p·s; s is huge, so p must be tiny."**

### 8Connect the Dots

Step 3 of a page fault needs a frame. When none is free, which page should be thrown out? The next lesson compares the replacement policies GATE asks about: **FIFO, optimal and LRU**, and a strange effect called **Belady's anomaly**.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**NAT2 marksEAT

Memory access 100 ns, page-fault service time 10 ms, page-fault rate 10⁻⁵. Effective access time in ns (nearest integer)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT2 marksDirty bit

Page-fault service takes 8 ms with a clean victim and 20 ms with a dirty one; 70% of victims are dirty. Average service time in ms?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT2 marksMax fault rate

ma = 200 ns, s = 8 ms. Largest page-fault rate (in units of 10⁻⁶, 2 decimals) such that EAT ≤ 220 ns?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**MCQ1 markSteps

On a page fault, which step comes last?

1. (A) Restart the instruction that faulted
2. (B) Find a free frame
3. (C) Update the page table
4. (D) Read the page from disk

**Q5**MCQ1 markCopy-on-write

Copy-on-write after fork() means:

1. (A) the parent is suspended
2. (B) the child cannot write
3. (C) pages are shared until one process writes to a page, which is then copied
4. (D) all pages are copied at fork time

### 10Rule Card

- Demand paging: load on first reference; valid bit = in memory.
- Page fault: trap → check → free frame (or victim) → disk read → update table → restart.
- EAT = (1 − p)·ma + p·s; ms = 10⁶ ns.
- Dirty victims must be written back; average s weighted by the dirty fraction.
- Copy-on-write makes fork() cheap.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

virtual memorydemand pagingpure demand pagingpage faultpage-fault handling stepspage-fault rateeffective access time with faultsdirty (modify) bitcopy-on-write

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. Whether the page is part of the process (a valid page).
2. t + 2m.
3. Swapping processes out of and back into memory.

#### Self-Test

**Q1** Answer: 2002 marks

0.99999 × 100 + 100 ≈ 199.999.

Re-read: [Lesson 5.3.1](#l-5-3-1) — Demand paging, page faults and effective access time

**Q2** Answer: 16.42 marks

0.3 × 8 + 0.7 × 20.

Re-read: [Lesson 5.3.1](#l-5-3-1) — Demand paging, page faults and effective access time

**Q3** Answer: 2.49 to 2.512 marks

200 + p(7,999,800) ≤ 220 → p ≤ 2.5 × 10⁻⁶.

Re-read: [Lesson 5.3.1](#l-5-3-1) — Demand paging, page faults and effective access time

**Q4** Answer: (A)1 mark

The faulting instruction runs again.

- **(B) is wrong:** Early.
- **(C) is wrong:** Before the restart.
- **(D) is wrong:** Before the table update.

Re-read: [Lesson 5.3.1](#l-5-3-1) — Demand paging, page faults and effective access time

**Q5** Answer: (C)1 mark

Copy only on a write.

- **(A) is wrong:** No.
- **(B) is wrong:** It can; a copy is made.
- **(D) is wrong:** That is what it avoids.

Re-read: [Lesson 5.3.1](#l-5-3-1) — Demand paging, page faults and effective access time

Type next → [**5.3.2** Page replacement: FIFO, optimal and LRU; Belady's anomaly](#l-5-3-2)

## 📄Lesson 5.3.2 — Page replacement: FIFO, optimal and LRU; Belady's anomaly

Phase 5 › Memory Management & Virtual Memory › Chapter 5.3 Virtual memory › Topic 5.3.2

Phase 5Ch 5.3 Virtual memoryTopic 5.3.2GATE weight: High≈ 55 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. EAT with page faults? from [Lesson 5.3.1](#l-5-3-1)
2. What happens in step 3 of a page fault if no frame is free? from [Lesson 5.3.1](#l-5-3-1)
3. What is FCFS's weakness in CPU scheduling? from [Lesson 2.1.1](#l-2-1-1)

### 1The Hook

🎣

Your desk holds three books; a fourth is needed. Which one goes back on the shelf: the one that has been on the desk longest, the one you won't need for the longest time, or the one you haven't opened for the longest time? These are **FIFO**, **optimal** and **LRU**, and counting their page faults on a reference string is one of the most common GATE questions in OS.

### 2Predict First

🤔

3 frames, all empty. Pages referenced: 1, 2, 3, 1, 4. With FIFO, how many page faults?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

1, 2, 3 fault (3), 1 hits, 4 faults and evicts 1 (the oldest) → **4 faults**.

🗣️

In plain words

Write the reference string across the page. Keep a column of frames under each reference. On a hit nothing changes. On a miss with a free frame, fill it. On a miss with no free frame, evict the page the policy chooses. Count the misses.

#### 1. The three policies

- **FIFO**: evict the page that has been in memory **longest** (loaded earliest).
- **Optimal (OPT)**: evict the page whose **next use is farthest in the future** (or never used again). Fewest faults possible; needs the future, so it is only a benchmark.
- **LRU (least recently used)**: evict the page **not used for the longest time** (looks at the past).

#### 2. Running example: 7 0 1 2 0 3 0 4 2 3 0 3 2, 3 frames

```
ref:    7 0 1 2 0 3 0 4 2 3 0 3 2
FIFO    7 7 7 2 2 2 2 4 4 4 0 0 0
        . 0 0 0 0 3 3 3 2 2 2 2 2
        . . 1 1 1 1 0 0 0 3 3 3 3
fault   F F F F - F F F F F F - -     10 faults

OPT     7 7 7 2 2 2 2 2 2 2 2 2 2
        . 0 0 0 0 0 0 4 4 4 0 0 0
        . . 1 1 1 3 3 3 3 3 3 3 3
fault   F F F F - F - F - - F - -      7 faults

LRU     7 7 7 2 2 2 2 4 4 4 0 0 0
        . 0 0 0 0 0 0 0 0 3 3 3 3
        . . 1 1 1 3 3 3 2 2 2 2 2
fault   F F F F - F - F F F F - -      9 faults
```

(Each row is one frame; the new page goes into the victim's frame.) With **4 frames**: FIFO 7, OPT 6, LRU 6.

#### 3. Belady's anomaly

Normally more frames → fewer (or equal) faults. With **FIFO** this can fail: string 1 2 3 4 1 2 5 1 2 3 4 5 → FIFO with 3 frames: **9** faults; with 4 frames: **10** faults. **LRU and OPT never show the anomaly** (they are "stack algorithms": the pages kept with n frames are always a subset of those kept with n + 1).

#### 4. Implementing LRU

Exact LRU needs hardware help on every access: a **counter** (time stamp) per page, or a **stack** of page numbers (move to top on use). That is expensive, so real systems use approximations based on a **reference bit** (next lesson).

#### 5. Quick bounds

Starting with empty frames: faults ≥ number of **distinct pages** in the string, and faults ≤ length of the string.

### 4Visual

| Frames | FIFO | LRU | OPT |
| --- | --- | --- | --- |
| 3 | 9 | 10 | 7 |
| 4 | **10** | 8 | 6 |

Belady's string 1 2 3 4 1 2 5 1 2 3 4 5: only FIFO gets worse when a frame is added.

### 5Worked Examples

Example 1 Easy

Running string, 3 frames, FIFO: which page is evicted when page 3 first arrives (6th reference)?

Solution

Frames hold 2, 0, 1 with 0 loaded earliest (at reference 2) → **0** is evicted.

Example 2 Medium

Running string, 3 frames, LRU: which page is evicted when page 4 arrives (8th reference)?

Solution

Frames 2, 0, 3; last uses: 2 at ref 4, 0 at ref 7, 3 at ref 6 → **2** is least recently used.

Example 3 GATE

Reference string 1 2 3 4 1 2 5 1 2 3 4 5 with OPT and 3 frames: number of faults?

Solution

**7**: 1, 2, 3 load; 4 evicts 3 (needed latest); 5 evicts 4; then 3 and 4 each evict a page that is never needed again.

### 6GATE Traps

⚠️

- FIFO evicts the oldest **loaded**, even if it was just used (hits don't refresh it).
- LRU evicts the least recently **used** (hits do refresh it).
- OPT looks **forward**; a page never used again is the perfect victim.
- Belady's anomaly: only FIFO-type algorithms; never LRU or OPT.

### 7Memory Hook

🧠

**"FIFO: oldest arrival. OPT: farthest future. LRU: longest past. More frames can hurt only FIFO."**

### 8Connect the Dots

Exact LRU is too costly. The last memory lesson approximates it with the **clock** algorithm, decides how many frames each process gets, and explains **thrashing**: what happens when every process has too few.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**NAT2 marksFIFO

Reference string 7 0 1 2 0 3 0 4 2 3 0 3 2, 4 frames (empty at first), FIFO. Number of page faults?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT2 marksLRU

Same string, 3 frames, LRU. Number of page faults?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT2 marksOPT

Same string, 3 frames, optimal replacement. Number of page faults?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**NAT2 marksBelady

Reference string 1 2 3 4 1 2 5 1 2 3 4 5, FIFO with 4 frames. Number of page faults?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**MSQ2 marksBelady

Which algorithms can suffer from Belady's anomaly?

1. (A) Second chance (FIFO with a reference bit)
2. (B) FIFO
3. (C) Optimal
4. (D) LRU

### 10Rule Card

- FIFO: evict earliest loaded. OPT: evict farthest next use (never used = best). LRU: evict least recently used.
- Running string, 3 frames: FIFO 10, OPT 7, LRU 9; 4 frames: FIFO 7, OPT 6, LRU 6.
- Belady (FIFO): 1 2 3 4 1 2 5 1 2 3 4 5 → 9 faults with 3 frames, 10 with 4. LRU and OPT are stack algorithms (no anomaly).
- Faults ≥ distinct pages (from empty); exact LRU needs counters or a stack.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

page replacementvictim pagereference stringFIFO replacementoptimal replacementLRU replacementBelady's anomalystack algorithmsimplementing LRU with counters or a stack

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. (1 − p)·ma + p·s.
2. A victim page is chosen and replaced.
3. The convoy effect.

#### Self-Test

**Q1** Answer: 72 marks

7, 0, 1, 2 load; 3 evicts 7; 4 evicts 0; 0 evicts 1.

Re-read: [Lesson 5.3.2](#l-5-3-2) — Page replacement: FIFO, optimal and LRU; Belady's anomaly

**Q2** Answer: 92 marks

See the trace.

Re-read: [Lesson 5.3.2](#l-5-3-2) — Page replacement: FIFO, optimal and LRU; Belady's anomaly

**Q3** Answer: 72 marks

See the trace.

Re-read: [Lesson 5.3.2](#l-5-3-2) — Page replacement: FIFO, optimal and LRU; Belady's anomaly

**Q4** Answer: 102 marks

More than the 9 faults with 3 frames.

Re-read: [Lesson 5.3.2](#l-5-3-2) — Page replacement: FIFO, optimal and LRU; Belady's anomaly

**Q5** Answer: (A) (B)2 marks

FIFO-based orders are not stack algorithms.

- **(C) is wrong:** Stack algorithm.
- **(D) is wrong:** Stack algorithm.

Re-read: [Lesson 5.3.2](#l-5-3-2) — Page replacement: FIFO, optimal and LRU; Belady's anomaly

Type next → [**5.3.3** Frame allocation, thrashing, working sets and the clock algorithm](#l-5-3-3)

## 📄Lesson 5.3.3 — Frame allocation, thrashing, working sets and the clock algorithm

Phase 5 › Memory Management & Virtual Memory › Chapter 5.3 Virtual memory › Topic 5.3.3

Phase 5Ch 5.3 Virtual memoryTopic 5.3.3GATE weight: Medium≈ 50 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. Which replacement policy can show Belady's anomaly? from [Lesson 5.3.2](#l-5-3-2)
2. EAT with page faults? from [Lesson 5.3.1](#l-5-3-1)
3. What happens to CPU utilisation when processes wait for I/O 80% of the time? from [Lesson 2.2.2](#l-2-2-2)

### 1The Hook

🎣

Juggling three balls is fine; give the juggler eight and he spends all his time picking balls off the floor. When processes don't have enough frames, they spend all their time page-faulting and the CPU sits idle: **thrashing**. This lesson shows how the OS shares frames, how it spots thrashing with the **working set**, and the cheap LRU substitute every real OS uses: the **clock** algorithm.

### 2Predict First

🤔

CPU utilisation is low, so the OS admits more processes. Each now gets fewer frames and faults more. What happens to CPU utilisation?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

It **drops further**: processes queue for the disk instead of using the CPU. The OS sees low utilisation and admits even more: the spiral called **thrashing**.

🗣️

In plain words

Each process needs a certain number of pages "at hand" to run smoothly (its **working set**). If the sum of everyone's working sets is more than the RAM, they keep stealing frames from each other and all of them fault constantly. The fix is to run fewer processes at once. For choosing victims cheaply, the **clock** gives every page a "second chance" if it was used recently.

#### 1. How many frames per process?

- **Equal allocation**: m frames, n processes → m/n each.
- **Proportional allocation**: process i of size sᵢ gets aᵢ = (sᵢ / S) × m, where S = Σ sᵢ.

  Example: 64 frames, sizes 20, 60, 80 pages (S = 160) → **8, 24, 32** frames.
- **Global replacement**: the victim may belong to any process (better throughput). **Local replacement**: only the process's own frames.

#### 2. Thrashing

High paging activity: a process spends more time paging than executing. Cause: degree of multiprogramming too high, so working sets don't fit. Cure: **reduce** the degree of multiprogramming (suspend processes), or give processes the frames they need.

#### 3. Working-set model

- **Working set** WS(t, Δ) = the set of distinct pages referenced in the last **Δ** references (up to time t). Δ is the "window".
- WSSᵢ = size of process i's working set; **D = Σ WSSᵢ** = total demand.
- If **D > m** (frames available) → thrashing → suspend a process. If D is well below m, another process can be admitted.

Example (running string 7 0 1 2 0 3 0 4 2 3 0 3 2, positions 1 to 13, Δ = 4):

- At t = 10 the last four references are 0 4 2 3 → WS = {0, 2, 3, 4}, size **4**.
- At t = 13 they are 3 0 3 2 → WS = {0, 2, 3}, size **3**.

#### 4. Page-fault frequency (PFF)

Set an upper and a lower bound on each process's fault rate: above the upper bound → give it more frames; below the lower bound → take frames away.

#### 5. Clock (second-chance) algorithm

Frames in a circle with a pointer; each page has a **reference bit**, set to 1 whenever the page is used (and when it is loaded). To find a victim: look at the page under the pointer.

- Bit = 1 → set it to 0 (second chance) and move on.
- Bit = 0 → replace this page; the new page gets bit 1; the pointer moves past it.

If every bit is 1, the clock goes round once and becomes FIFO. Running string, 3 frames:

```
ref  frames     bits   pointer after
7    7 . .      1 0 0  -> slot 1      F
0    7 0 .      1 1 0  -> slot 2      F
1    7 0 1      1 1 1  -> slot 0      F
2    2 0 1      1 0 0  -> slot 1      F   (all bits cleared, 7 replaced)
0    2 0 1      1 1 0  -> slot 1      hit
3    2 0 3      1 0 1  -> slot 0      F   (0 gets a second chance; 1 replaced)
0    2 0 3      1 1 1  -> slot 0      hit
4    4 0 3      1 0 0  -> slot 1      F
2    4 2 3      1 1 0  -> slot 2      F
3    4 2 3      1 1 1  -> slot 2      hit
0    4 2 0      0 0 1  -> slot 0      F   (full circle: all cleared, 3 replaced)
3    3 2 0      1 0 1  -> slot 1      F
2    3 2 0      1 1 1  -> slot 1      hit
```

**9 faults** (the same as LRU here). **Enhanced second chance** also looks at the dirty bit and prefers victims with (reference, dirty) = (0, 0), then (0, 1), (1, 0), (1, 1).

### 4Visual

Adding processes helps until their working sets no longer fit in memory; after that, utilisation collapses.

### 5Worked Examples

Example 1 Easy

93 frames are shared equally by 3 processes. Frames each?

Solution

93 / 3 = **31**.

Example 2 Medium

Proportional allocation: 100 frames, processes of 30 and 120 pages. Frames for the smaller one?

Solution

30 / 150 × 100 = **20**.

Example 3 GATE

Three processes have working-set sizes 18, 25 and 30 pages; the system has 70 frames. What should the OS do?

Solution

D = 73 > 70 → thrashing risk: **suspend a process** (reduce the degree of multiprogramming).

### 6GATE Traps

⚠️

- Thrashing is fixed by **fewer** processes, not more.
- Working set counts **distinct** pages in the window.
- In the clock algorithm a hit only sets the bit; it doesn't move the pointer.
- Proportional allocation uses process sizes, not priorities (unless told).

### 7Memory Hook

🧠

**"Too many jugglers' balls → thrashing. Working set = distinct pages in the last Δ. Clock: 1 → clear and pass; 0 → out."**

### 8Connect the Dots

Phase 5 is complete. Memory holds what is running; everything else lives in **files** on a disk. Phase 6 covers how files are stored and found, and how the OS drives disks and other I/O devices.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**NAT1 markProportional allocation

64 frames; three processes of 20, 60 and 80 pages. Frames for the 80-page process (proportional allocation)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT2 marksWorking set

Reference string 7 0 1 2 0 3 0 4 2 3 0 3 2 (positions 1–13), window Δ = 5. Size of the working set at t = 10?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT2 marksClock

Running string 7 0 1 2 0 3 0 4 2 3 0 3 2, 4 frames, clock algorithm (bit set on load and on use). Number of page faults?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**MCQ1 markThrashing

The best response to thrashing is to:

1. (A) reduce the page size to 1 byte
2. (B) use a faster CPU
3. (C) admit more processes
4. (D) reduce the degree of multiprogramming

**Q5**MCQ1 markClock

In the clock algorithm, the pointer reaches a page with reference bit 1. What happens?

1. (A) The page is replaced
2. (B) The bit is cleared and the pointer moves on
3. (C) The page is locked
4. (D) The page is written to disk

### 10Rule Card

- Equal: m/n. Proportional: aᵢ = sᵢ/S × m. Global vs local replacement.
- Thrashing: more paging than work; cure by reducing multiprogramming.
- Working set: distinct pages in last Δ references; D = Σ WSS > m → suspend someone. PFF bounds.
- Clock: bit 1 → clear and move; bit 0 → replace (new page bit 1). Enhanced: prefer (0,0).

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

equal allocationproportional allocationglobal vs local replacementthrashingdegree of multiprogrammingworking-set modelworking-set windowtotal demand Dpage-fault frequencyreference bitclock (second-chance) algorithmenhanced second chance

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. FIFO.
2. (1 − p)·ma + p·s.
3. It is roughly 1 − 0.8ⁿ for n processes.

#### Self-Test

**Q1** Answer: 321 mark

80/160 × 64.

Re-read: [Lesson 5.3.3](#l-5-3-3) — Frame allocation, thrashing, working sets and the clock algorithm

**Q2** Answer: 42 marks

References 6–10: 3 0 4 2 3 → {0, 2, 3, 4}.

Re-read: [Lesson 5.3.3](#l-5-3-3) — Frame allocation, thrashing, working sets and the clock algorithm

**Q3** Answer: 62 marks

Only first loads and two replacements.

Re-read: [Lesson 5.3.3](#l-5-3-3) — Frame allocation, thrashing, working sets and the clock algorithm

**Q4** Answer: (D)1 mark

Free frames for the remaining processes.

- **(A) is wrong:** Nonsense.
- **(B) is wrong:** The CPU isn't the bottleneck.
- **(C) is wrong:** Makes it worse.

Re-read: [Lesson 5.3.3](#l-5-3-3) — Frame allocation, thrashing, working sets and the clock algorithm

**Q5** Answer: (B)1 mark

A second chance.

- **(A) is wrong:** Only bit 0 pages are replaced.
- **(C) is wrong:** No.
- **(D) is wrong:** Only dirty victims are written.

Re-read: [Lesson 5.3.3](#l-5-3-3) — Frame allocation, thrashing, working sets and the clock algorithm

Type next → [**LI-5.3** Chapter 5.3 Lock-in](#l-LI-5-3)

## 🔒Chapter 5.3 Lock-in — Virtual memory

Phase 5 › Memory Management & Virtual Memory › Chapter 5.3 Virtual memory

Phase 5Ch 5.3 Virtual memory

### ACompressed recap

🧾

Demand paging: page fault → trap, find frame, disk read, update table, restart. EAT = (1 − p)·ma + p·s (ms = 10⁶ ns); dirty victims cost a write. Copy-on-write. FIFO (oldest loaded), OPT (farthest future), LRU (least recently used); running string 3 frames: 10, 7, 9. Belady: FIFO 9 → 10 faults with 3 → 4 frames; LRU/OPT immune. Allocation equal / proportional; thrashing → reduce multiprogramming; working set = distinct pages in last Δ; clock gives second chances.

### BMerged rule card

[5.3.1](#l-5-3-1) Demand paging, page faults and effective access time

- Demand paging: load on first reference; valid bit = in memory.
- Page fault: trap → check → free frame (or victim) → disk read → update table → restart.
- EAT = (1 − p)·ma + p·s; ms = 10⁶ ns.
- Dirty victims must be written back; average s weighted by the dirty fraction.
- Copy-on-write makes fork() cheap.

[5.3.2](#l-5-3-2) Page replacement: FIFO, optimal and LRU; Belady's anomaly

- FIFO: evict earliest loaded. OPT: evict farthest next use (never used = best). LRU: evict least recently used.
- Running string, 3 frames: FIFO 10, OPT 7, LRU 9; 4 frames: FIFO 7, OPT 6, LRU 6.
- Belady (FIFO): 1 2 3 4 1 2 5 1 2 3 4 5 → 9 faults with 3 frames, 10 with 4. LRU and OPT are stack algorithms (no anomaly).
- Faults ≥ distinct pages (from empty); exact LRU needs counters or a stack.

[5.3.3](#l-5-3-3) Frame allocation, thrashing, working sets and the clock algorithm

- Equal: m/n. Proportional: aᵢ = sᵢ/S × m. Global vs local replacement.
- Thrashing: more paging than work; cure by reducing multiprogramming.
- Working set: distinct pages in last Δ references; D = Σ WSS > m → suspend someone. PFF bounds.
- Clock: bit 1 → clear and move; bit 0 → replace (new page bit 1). Enhanced: prefer (0,0).

### CInterleaved GATE-style questions

**Q1**NAT2 marksEAT

ma = 200 ns, s = 8 ms, p = 0.001. EAT in ns (1 decimal)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**MCQ1 markValid bit

In demand paging, valid bit 0 for a legal page means:

1. (A) the page is dirty
2. (B) the page is on disk, not in memory
3. (C) the page is in memory
4. (D) the page is shared

**Q3**NAT2 marksFIFO

Reference string 1 2 3 4 1 2 5 1 2 3 4 5, FIFO, 3 frames. Number of faults?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**NAT2 marksLRU

Reference string 1 2 3 4 1 2 5 1 2 3 4 5, LRU, 4 frames. Number of faults?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**NAT1 markLower bound

Running string 7 0 1 2 0 3 0 4 2 3 0 3 2 with 10 empty frames. Number of faults under any policy?

Numerical answer: \_\_\_\_\_\_\_\_

**Q6**NAT1 markAllocation

Proportional allocation of 100 frames to processes of 30 and 120 pages: frames for the larger process?

Numerical answer: \_\_\_\_\_\_\_\_

**Q7**NAT2 marksWorking set

Running string (positions 1–13), Δ = 3. Working-set size at t = 9?

Numerical answer: \_\_\_\_\_\_\_\_

**Q8**MCQ1 markThrashing

Thrashing occurs when:

1. (A) the disk is idle
2. (B) the TLB hit ratio is 1
3. (C) the sum of the working sets exceeds the available frames
4. (D) a process has too many frames

### DAnswer Vault

🔐 Open the Answer Vault

**Q1** Answer: 8199.7 to 8199.92 marks

0.999 × 200 + 0.001 × 8,000,000.

Re-read: [Lesson 5.3.1](#l-5-3-1) — Demand paging, page faults and effective access time

**Q2** Answer: (B)1 mark

Touching it causes a page fault.

- **(A) is wrong:** That is the dirty bit.
- **(C) is wrong:** That is valid = 1.
- **(D) is wrong:** Unrelated.

Re-read: [Lesson 5.3.1](#l-5-3-1) — Demand paging, page faults and effective access time

**Q3** Answer: 92 marks

The smaller-memory case of Belady's string.

Re-read: [Lesson 5.3.2](#l-5-3-2) — Page replacement: FIFO, optimal and LRU; Belady's anomaly

**Q4** Answer: 82 marks

1, 2, 3, 4 load; 5 evicts 3; 3 evicts 4; 4 evicts 5; 5 evicts 1.

Re-read: [Lesson 5.3.2](#l-5-3-2) — Page replacement: FIFO, optimal and LRU; Belady's anomaly

**Q5** Answer: 61 mark

Six distinct pages, each loaded once.

Re-read: [Lesson 5.3.2](#l-5-3-2) — Page replacement: FIFO, optimal and LRU; Belady's anomaly

**Q6** Answer: 801 mark

120/150 × 100.

Re-read: [Lesson 5.3.3](#l-5-3-3) — Frame allocation, thrashing, working sets and the clock algorithm

**Q7** Answer: 32 marks

References 7–9: 0 4 2 → {0, 2, 4}.

Re-read: [Lesson 5.3.3](#l-5-3-3) — Frame allocation, thrashing, working sets and the clock algorithm

**Q8** Answer: (C)1 mark

Processes keep stealing frames.

- **(A) is wrong:** The disk is overloaded.
- **(B) is wrong:** Ideal TLB.
- **(D) is wrong:** Too few frames.

Re-read: [Lesson 5.3.3](#l-5-3-3) — Frame allocation, thrashing, working sets and the clock algorithm

Type next → [**CP-5** Phase 5 Checkpoint (15 questions)](#l-CP-5)

## ⏱️Phase 5 Checkpoint — Memory Management & Virtual Memory

Phase 5 › Memory Management & Virtual Memory

Phase 5

Phase 5 Checkpoint: 15 questions on memory management and virtual memory.

⏱️

**15 questions · 24 marks · 45 minutes.** Negative marking on MCQ only: −1/3 mark for a wrong 1-mark MCQ, −2/3 for a wrong 2-mark MCQ. No negative marking for MSQ or NAT; MSQ has no partial credit.

**Q1**NAT1 markBase/limit

Base 1200, limit 400. Physical address for logical address 399?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**MCQ1 markBest fit

Holes 100, 500, 200, 300, 600 KB. With best fit, where does a 212 KB request go?

1. (A) 600 KB hole
2. (B) 500 KB hole
3. (C) 200 KB hole
4. (D) 300 KB hole

**Q3**NAT2 marksFirst fit

Holes 100, 500, 200, 300, 600 KB; requests 212, 417, 112, 426 KB with first fit. How many requests cannot be placed?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**NAT1 markAddress split

A 36-bit logical address with 16 KB pages: number of offset bits?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**NAT2 marksPage table

32-bit logical addresses, 1 KB pages, 2-byte entries. Page-table size in MB?

Numerical answer: \_\_\_\_\_\_\_\_

**Q6**NAT2 marksTranslation

Pages are 4 KB. Logical address 20,000 is on page p, and page p is in frame 3. Physical address?

Numerical answer: \_\_\_\_\_\_\_\_

**Q7**NAT2 marksEAT

Memory 100 ns, TLB 20 ns, hit ratio 0.98 (single level). EAT in ns?

Numerical answer: \_\_\_\_\_\_\_\_

**Q8**NAT2 marksLevels

46-bit virtual addresses, 8 KB pages, 4-byte entries, each table one page. Levels?

Numerical answer: \_\_\_\_\_\_\_\_

**Q9**MCQ1 markSegmentation

Segment 1 has base 5000 and limit 300. Logical address (1, 350):

1. (A) trap
2. (B) 5050
3. (C) 5350
4. (D) 350

**Q10**NAT2 marksEAT with faults

ma = 100 ns, s = 10 ms. Largest page-fault rate (in units of 10⁻⁶, 2 decimals) so that EAT ≤ 110 ns?

Numerical answer: \_\_\_\_\_\_\_\_

**Q11**MCQ1 markDirty bit

The dirty bit lets the OS:

1. (A) detect illegal addresses
2. (B) skip writing a victim page back to disk when it wasn't modified
3. (C) find the least recently used page
4. (D) share pages after fork()

**Q12**NAT2 marksFIFO

Running string 7 0 1 2 0 3 0 4 2 3 0 3 2, 3 frames, FIFO. Faults?

Numerical answer: \_\_\_\_\_\_\_\_

**Q13**NAT2 marksOPT

Running string, 4 frames, optimal. Faults?

Numerical answer: \_\_\_\_\_\_\_\_

**Q14**NAT2 marksClock

Running string, 3 frames, clock algorithm (bit set on load and on use). Faults?

Numerical answer: \_\_\_\_\_\_\_\_

**Q15**NAT1 markEqual allocation

120 frames shared equally among 8 processes: frames each?

Numerical answer: \_\_\_\_\_\_\_\_

### ✓Answer Vault

🔐 Open the Answer Vault

**Q1** Answer: 15991 mark

Inside the limit.

Re-read: [Lesson 5.1.1](#l-5-1-1) — Addresses and contiguous allocation: fits and fragmentation

**Q2** Answer: (D)1 mark

Smallest hole that fits.

- **(A) is wrong:** Largest.
- **(B) is wrong:** Larger than needed.
- **(C) is wrong:** Too small.

Re-read: [Lesson 5.1.1](#l-5-1-1) — Addresses and contiguous allocation: fits and fragmentation

**Q3** Answer: 12 marks

212 → 500, 417 → 600, 112 → 288, and 426 fails.

Re-read: [Lesson 5.1.1](#l-5-1-1) — Addresses and contiguous allocation: fits and fragmentation

**Q4** Answer: 141 mark

2¹⁴ = 16 K.

Re-read: [Lesson 5.2.1](#l-5-2-1) — Paging: pages, frames, page tables and the address split

**Q5** Answer: 82 marks

2²² entries × 2 B.

Re-read: [Lesson 5.2.1](#l-5-2-1) — Paging: pages, frames, page tables and the address split

**Q6** Answer: 159042 marks

p = 4, offset 20,000 − 16,384 = 3,616; 3 × 4096 + 3,616.

Re-read: [Lesson 5.2.1](#l-5-2-1) — Paging: pages, frames, page tables and the address split

**Q7** Answer: 1222 marks

0.98 × 120 + 0.02 × 220.

Re-read: [Lesson 5.2.2](#l-5-2-2) — TLBs, effective access time and multilevel page tables

**Q8** Answer: 32 marks

33 page bits / 11.

Re-read: [Lesson 5.2.2](#l-5-2-2) — TLBs, effective access time and multilevel page tables

**Q9** Answer: (A)1 mark

350 ≥ 300.

- **(B) is wrong:** Wrong arithmetic.
- **(C) is wrong:** Outside the segment.
- **(D) is wrong:** Base missing.

Re-read: [Lesson 5.2.3](#l-5-2-3) — Segmentation, and segmentation with paging

**Q10** Answer: 0.99 to 1.012 marks

p ≤ 10 / 9,999,900.

Re-read: [Lesson 5.3.1](#l-5-3-1) — Demand paging, page faults and effective access time

**Q11** Answer: (B)1 mark

Clean pages are already on disk.

- **(A) is wrong:** Valid bit / limits.
- **(C) is wrong:** That needs reference information.
- **(D) is wrong:** Copy-on-write.

Re-read: [Lesson 5.3.1](#l-5-3-1) — Demand paging, page faults and effective access time

**Q12** Answer: 102 marks

See Lesson 5.3.2.

Re-read: [Lesson 5.3.2](#l-5-3-2) — Page replacement: FIFO, optimal and LRU; Belady's anomaly

**Q13** Answer: 62 marks

The six first loads only.

Re-read: [Lesson 5.3.2](#l-5-3-2) — Page replacement: FIFO, optimal and LRU; Belady's anomaly

**Q14** Answer: 92 marks

See the trace in Lesson 5.3.3.

Re-read: [Lesson 5.3.3](#l-5-3-3) — Frame allocation, thrashing, working sets and the clock algorithm

**Q15** Answer: 151 mark

120 / 8.

Re-read: [Lesson 5.3.3](#l-5-3-3) — Frame allocation, thrashing, working sets and the clock algorithm

Type next → [**6.1.1** Files, directories and access methods](#l-6-1-1)

# 💾Phase 6 — File Systems & I/O

## 📄Lesson 6.1.1 — Files, directories and access methods

Phase 6 › File Systems & I/O › Chapter 6.1 File systems › Topic 6.1.1

Phase 6Ch 6.1 File systemsTopic 6.1.1GATE weight: Low≈ 35 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. What does the clock algorithm do with a page whose reference bit is 1? from [Lesson 5.3.3](#l-5-3-3)
2. Which system call creates a new process? from [Lesson 1.1.2](#l-1-1-2)
3. What does the OS keep about each process in a PCB? from [Lesson 1.1.1](#l-1-1-1)

### 1The Hook

🎣

Your phone has thousands of photos, yet you find one in seconds by opening "Photos → 2026 → Goa". **Files** give data a name, and **directories** organise the names. This lesson is light in GATE terms, but the words it introduces (open-file table, hard link, rwx bits) are used in every later file-system question.

### 2Predict First

🤔

A file has permissions shown as `rwxr-x---`. Can a user who is not the owner and not in the file's group read it?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

**No.** The last three characters (`---`) are the permissions for "others": nothing allowed.

🗣️

In plain words

A **file** is a named collection of data kept on disk. The OS remembers facts about it (its **attributes**), offers operations on it (open, read, write, close), and keeps files in **directories** so names can be found. Permissions say who may do what.

#### 1. File attributes and operations

- Attributes: name, type, size, location on disk, protection, owner, timestamps. Kept in a per-file record (in UNIX, the **inode**: Lesson 6.1.2).
- Operations: create, **open**, read, write, **seek** (move the file pointer), close, delete, truncate.
- `open()` finds the file once and returns a small number (file descriptor), so later reads don't search again.

#### 2. Open-file tables

- **System-wide open-file table**: one entry per open file (location, size, **open count**).
- **Per-process table**: for each file the process opened, its **file pointer** (current position) and access mode, pointing to the system-wide entry.
- When the open count drops to 0 on close, the system-wide entry is removed.

#### 3. Access methods

- **Sequential**: read the next record, then the next (like a tape). Most common.
- **Direct (relative)**: jump straight to block n (databases).
- **Indexed**: an index of keys points to blocks; search the index, then jump.

#### 4. Directory structures

| Structure | Idea | Problem / feature |
| --- | --- | --- |
| Single-level | one directory for everyone | names clash |
| Two-level | one directory per user | no grouping inside a user |
| Tree | directories inside directories | **absolute** path (from root) and **relative** path (from current directory) |
| Acyclic graph | a file can appear in two directories (**links**) | deleting must handle shared files |
| General graph | cycles allowed | needs cycle checks / garbage collection |

Links:

- **Hard link**: another directory entry for the **same inode**; the inode keeps a **link count**, and data is freed only when it reaches 0.
- **Soft (symbolic) link**: a small file that stores a **path**; it breaks if the target is deleted.

#### 5. Protection: UNIX permission bits

Three groups (owner, group, others) × three rights (read r, write w, execute x) = **9 bits**, usually written in octal: r = 4, w = 2, x = 1. `754` = owner 7 (rwx), group 5 (r-x), others 4 (r--) → `rwxr-xr--`. Access-control lists (ACLs) can list rights per individual user.

### 4Visual

A tree directory (blue = directories, green = files). Absolute path of os.pdf: /home/asha/gate/os.pdf; from /home/asha the relative path is gate/os.pdf.

### 5Worked Examples

Example 1 Easy

Write permissions `rw-r-----` in octal.

Solution

owner rw- = 6, group r-- = 4, others --- = 0 → **640**.

Example 2 Medium

A file has two hard links. One of them is deleted. Is the file's data freed?

Solution

**No.** The link count drops from 2 to 1; data is freed only at 0.

Example 3 GATE

A symbolic link points to /home/asha/a.txt, and a.txt is then deleted. What happens when the link is opened?

Solution

It **fails** (dangling link): the soft link only stores the path.

### 6GATE Traps

⚠️

- Octal digits: r = 4, w = 2, x = 1; order is owner, group, others.
- Hard links share the inode; soft links store a path.
- The file pointer is **per process** (per open), not per file.
- Sequential access is the default; direct access needs block numbers.

### 7Memory Hook

🧠

**"rwx = 4 2 1; owner-group-others. Hard link = same inode; soft link = just a path."**

### 8Connect the Dots

The directory entry tells us **which** file; the next lesson shows **where its blocks are**: contiguous, linked (FAT) or indexed (inodes), and how free blocks are tracked.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**NAT1 markPermissions

What octal number represents `rwxr-x--x`?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**MCQ1 markPermissions

Permissions `640` on a file mean the group can:

1. (A) read only
2. (B) read and write
3. (C) nothing
4. (D) execute only

**Q3**MCQ1 markLinks

Which statement about hard links is true?

1. (A) Deleting the original name always frees the data
2. (B) Hard links break when the target is renamed
3. (C) A hard link is another name for the same inode
4. (D) A hard link stores the target's path

**Q4**MCQ1 markOpen-file table

Where is the current file pointer (read/write position) kept?

1. (A) In the inode
2. (B) In the directory entry
3. (C) In the disk's boot block
4. (D) In the per-process open-file entry

**Q5**MCQ1 markAccess methods

Reading record 500 without reading records 0–499 first requires:

1. (A) a single-level directory
2. (B) a symbolic link
3. (C) sequential access
4. (D) direct access

### 10Rule Card

- File: attributes + operations; open() returns a descriptor; seek moves the pointer.
- System-wide table (open count) + per-process table (file pointer).
- Access: sequential, direct, indexed. Directories: single, two-level, tree (absolute/relative paths), acyclic graph, general graph.
- Hard link = same inode, link count; soft link = path (can dangle).
- UNIX rwx bits: owner/group/others, r4 w2 x1 (e.g. 754 = rwxr-xr--).

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

filefile attributesfile operationsopen-file tablesfile pointeropen countsequential accessdirect accessindexed accessdirectory structuresabsolute and relative pathshard linksoft (symbolic) linklink countpermission bitsaccess-control list

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. Clears the bit and moves on (second chance).
2. fork().
3. State, PC, registers, memory and file information, etc.

#### Self-Test

**Q1** Answer: 7511 mark

7, 5, 1.

Re-read: [Lesson 6.1.1](#l-6-1-1) — Files, directories and access methods

**Q2** Answer: (A)1 mark

Middle digit 4 = r--.

- **(B) is wrong:** That would be 6.
- **(C) is wrong:** That would be 0.
- **(D) is wrong:** That would be 1.

Re-read: [Lesson 6.1.1](#l-6-1-1) — Files, directories and access methods

**Q3** Answer: (C)1 mark

Same inode, link count increases.

- **(A) is wrong:** Only when the count reaches 0.
- **(B) is wrong:** Renaming doesn't affect other names.
- **(D) is wrong:** That is a soft link.

Re-read: [Lesson 6.1.1](#l-6-1-1) — Files, directories and access methods

**Q4** Answer: (D)1 mark

Each open has its own position.

- **(A) is wrong:** The inode is shared.
- **(B) is wrong:** Directories hold names.
- **(C) is wrong:** No.

Re-read: [Lesson 6.1.1](#l-6-1-1) — Files, directories and access methods

**Q5** Answer: (D)1 mark

Jump to the record.

- **(A) is wrong:** Unrelated.
- **(B) is wrong:** Unrelated.
- **(C) is wrong:** Would read everything before it.

Re-read: [Lesson 6.1.1](#l-6-1-1) — Files, directories and access methods

Type next → [**6.1.2** Allocation methods: contiguous, linked (FAT), indexed (inodes); free space](#l-6-1-2)

## 📄Lesson 6.1.2 — Allocation methods: contiguous, linked (FAT), indexed (inodes); free space

Phase 6 › File Systems & I/O › Chapter 6.1 File systems › Topic 6.1.2

Phase 6Ch 6.1 File systemsTopic 6.1.2GATE weight: High≈ 55 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. What does a hard link share with the original name? from [Lesson 6.1.1](#l-6-1-1)
2. What octal number is `rw-r--r--`? from [Lesson 6.1.1](#l-6-1-1)
3. What is external fragmentation? from [Lesson 5.1.1](#l-5-1-1)

### 1The Hook

🎣

A disk is a long row of numbered blocks. A file needs some of them. Where do they go, and how do we find block 700 of a file quickly? There are three classic answers, each with a GATE favourite: contiguous (fast but fragments), linked/FAT (count pointer hops, size of the FAT), and indexed/inode (**maximum file size** with direct and indirect pointers, asked in many papers).

### 2Predict First

🤔

A file's blocks are linked: each block stores the number of the next block. How many disk reads are needed to reach block 100 of the file (blocks numbered from 0)?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

**101**: blocks 0, 1, …, 100 must each be read to follow the chain.

🗣️

In plain words

Contiguous: give the file one unbroken run of blocks. Linked: let the blocks be anywhere, each pointing to the next. Indexed: let the blocks be anywhere, and keep a separate list (index) of all of them. UNIX's inode is an index that uses extra levels of index blocks for big files.

#### 1. Contiguous allocation

- Directory stores (start block, length). Block b of the file is disk block **start + b**.
- Fast sequential and direct access.
- **External fragmentation**; hard to let a file grow.

#### 2. Linked allocation and the FAT

- Each block holds a pointer to the next; the directory stores the first (and last) block.
- No external fragmentation; files grow easily.
- Direct access is slow: reaching block b needs **b + 1** reads. Pointers use space; one bad pointer loses the rest of the file.
- **FAT (file-allocation table)**: move all the "next" pointers into one table at the start of the disk, **one entry per disk block**. Cached in memory, the chain is followed without disk reads.

  **FAT size = number of disk blocks × entry size.** 2 GB disk, 4 KB blocks → 2¹⁹ blocks; 4-byte entries → **2 MB**.

#### 3. Indexed allocation and the UNIX inode

- Each file has an **index block** listing its blocks; block b = index\[b\]. Direct access; no external fragmentation; the index costs space.
- **Inode**: a few **direct** pointers plus a **single indirect** (points to a block full of pointers), a **double indirect** and a **triple indirect** pointer.
- With block size B and pointer size P, one block holds **k = B / P** pointers:

  **Max file size = (direct + k + k² + k³) × B** (drop the terms for pointers that don't exist). Example: 12 direct, B = 4 KB, P = 4 B → k = 1024 → (12 + 1024 + 2²⁰ + 2³⁰) × 4 KB ≈ **4 TB**.
- Disk reads to fetch a data block (inode already in memory): direct 1, single indirect 2, double 3, triple 4.

#### 4. Free-space management

- **Bit vector (bitmap)**: one bit per block (1 = free, or 0 = free, by convention). Size = number of blocks / 8 bytes. 1 TB disk, 4 KB blocks → 2²⁸ bits = **32 MB**.
- **Linked list** of free blocks (no wasted space, slow to find many).
- **Grouping**: the first free block stores addresses of n free blocks.
- **Counting**: store (first free block, how many follow).

### 4Visual

```
UNIX inode (block size B, k = B / P pointers per block)

 inode
 +----------------+
 | direct 0..11   |---> 12 data blocks
 | single indirect|---> [k pointers] ---> k data blocks
 | double indirect|---> [k] -> [k] each ---> k^2 data blocks
 | triple indirect|---> [k] -> [k] -> [k] ---> k^3 data blocks
 +----------------+
 max size = (12 + k + k^2 + k^3) x B
```

### 5Worked Examples

Example 1 Easy

Contiguous allocation: a file starts at block 300 and is 20 blocks long. Which disk block holds file block 7?

Solution

300 + 7 = **307**.

Example 2 Medium

Inode with 10 direct pointers, one single and one double indirect pointer; blocks are 256 bytes; pointers 8 bytes. Maximum file size?

Solution

k = 32. (10 + 32 + 32²) × 256 = 1066 × 256 = **272,896 bytes** (266.5 KB).

Example 3 GATE

4 KB blocks, 4-byte pointers, 12 direct pointers. The inode is in memory. How many disk reads are needed to read byte 10,000,000 of the file?

Solution

Block number 10,000,000 / 4096 → block 2441. Direct covers 0–11, single indirect covers 12–1035, so 2441 is in the **double indirect** range → 2 index blocks + 1 data block = **3 reads**.

### 6GATE Traps

⚠️

- k = block size / pointer size: compute it first.
- Use the **pointer** counts the inode really has (drop k³ if there is no triple indirect).
- FAT has one entry per **disk block**, not per file.
- Linked allocation: block b needs b + 1 reads (blocks numbered from 0).

### 7Memory Hook

🧠

**"Contiguous = start + b. Linked = follow b pointers (FAT keeps them in memory). Inode = (direct + k + k² + k³) × B."**

### 8Connect the Dots

Chapter 6.1 is complete. Every block read is a trip to the disk, and disks are slow because a head must move. Chapter 6.2 opens the disk up: its geometry, its access time, and the order in which to serve requests.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**NAT2 marksInode size

Inode with 8 direct pointers, 1 single and 1 double indirect pointer; block size 512 bytes; pointer size 4 bytes. Maximum file size in bytes?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT2 marksFAT

A 2 GB disk uses 4 KB blocks and a FAT with 4-byte entries. FAT size in MB?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT1 markBitmap

A 1 TB disk with 4 KB blocks uses a free-space bitmap. Bitmap size in MB?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**NAT2 marksDisk reads

Inode with 12 direct pointers, 4 KB blocks, 4-byte pointers; inode in memory. How many disk reads to fetch file block 500?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**MCQ1 markMethods

Which allocation method gives fast direct access but suffers from external fragmentation?

1. (A) FAT
2. (B) Indexed
3. (C) Contiguous
4. (D) Linked

### 10Rule Card

- Contiguous: (start, length), block b = start + b; external fragmentation.
- Linked: next pointers; block b needs b + 1 reads. FAT = one entry per disk block, cached.
- Indexed/inode: k = B/P; max size = (direct + k + k² + k³) × B; reads: direct 1, single 2, double 3, triple 4.
- Free space: bitmap (blocks/8 bytes), linked list, grouping, counting.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

disk blockscontiguous allocationlinked allocationfile-allocation tableindexed allocationindex blockinodedirect, single, double and triple indirect pointersmaximum file sizefree-space bitmapfree listgroupingcounting

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. The inode.
2. 644.
3. Free space split into pieces too small to use.

#### Self-Test

**Q1** Answer: 84582402 marks

k = 128; (8 + 128 + 16384) × 512.

Re-read: [Lesson 6.1.2](#l-6-1-2) — Allocation methods: contiguous, linked (FAT), indexed (inodes); free space

**Q2** Answer: 22 marks

2¹⁹ entries × 4 B.

Re-read: [Lesson 6.1.2](#l-6-1-2) — Allocation methods: contiguous, linked (FAT), indexed (inodes); free space

**Q3** Answer: 321 mark

2²⁸ bits = 2²⁵ bytes.

Re-read: [Lesson 6.1.2](#l-6-1-2) — Allocation methods: contiguous, linked (FAT), indexed (inodes); free space

**Q4** Answer: 22 marks

500 is in the single-indirect range (12–1035): index block + data block.

Re-read: [Lesson 6.1.2](#l-6-1-2) — Allocation methods: contiguous, linked (FAT), indexed (inodes); free space

**Q5** Answer: (C)1 mark

start + b, but needs free runs.

- **(A) is wrong:** Linked with the pointers in a table.
- **(B) is wrong:** No external fragmentation.
- **(D) is wrong:** Slow direct access, no external fragmentation.

Re-read: [Lesson 6.1.2](#l-6-1-2) — Allocation methods: contiguous, linked (FAT), indexed (inodes); free space

Type next → [**LI-6.1** Chapter 6.1 Lock-in](#l-LI-6-1)

## 🔒Chapter 6.1 Lock-in — File systems

Phase 6 › File Systems & I/O › Chapter 6.1 File systems

Phase 6Ch 6.1 File systems

### ACompressed recap

🧾

File = attributes + operations; per-process table holds the file pointer, system-wide table the open count. Access: sequential, direct, indexed. Directories: tree with absolute/relative paths; hard link = same inode (link count), soft link = path. rwx bits r4 w2 x1. Allocation: contiguous (start + b), linked (b + 1 reads; FAT one entry per block), indexed/inode (direct + k + k² + k³) × B with k = B/P. Bitmap = blocks/8 bytes.

### BMerged rule card

[6.1.1](#l-6-1-1) Files, directories and access methods

- File: attributes + operations; open() returns a descriptor; seek moves the pointer.
- System-wide table (open count) + per-process table (file pointer).
- Access: sequential, direct, indexed. Directories: single, two-level, tree (absolute/relative paths), acyclic graph, general graph.
- Hard link = same inode, link count; soft link = path (can dangle).
- UNIX rwx bits: owner/group/others, r4 w2 x1 (e.g. 754 = rwxr-xr--).

[6.1.2](#l-6-1-2) Allocation methods: contiguous, linked (FAT), indexed (inodes); free space

- Contiguous: (start, length), block b = start + b; external fragmentation.
- Linked: next pointers; block b needs b + 1 reads. FAT = one entry per disk block, cached.
- Indexed/inode: k = B/P; max size = (direct + k + k² + k³) × B; reads: direct 1, single 2, double 3, triple 4.
- Free space: bitmap (blocks/8 bytes), linked list, grouping, counting.

### CInterleaved GATE-style questions

**Q1**NAT1 markPermissions

Octal value of `r-xr-xr-x`?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**MCQ1 markSoft link

A symbolic link's target is deleted. The link:

1. (A) becomes dangling: opening it fails
2. (B) is deleted automatically
3. (C) becomes a hard link
4. (D) still opens the old data

**Q3**MCQ1 markDirectories

In a tree-structured directory, a relative path starts from:

1. (A) the root
2. (B) the current working directory
3. (C) the user's home directory always
4. (D) the disk's first block

**Q4**NAT2 marksInode

Inode with 10 direct, 1 single and 1 double indirect pointer; block 2 KB; pointer 4 bytes. Maximum file size in MB (2 decimals)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**NAT1 markLinked

Linked allocation (no FAT): how many disk reads to reach block 49 of a file (blocks numbered from 0)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q6**NAT1 markContiguous

A contiguous file starts at block 1200. Which disk block holds file block 35?

Numerical answer: \_\_\_\_\_\_\_\_

**Q7**NAT2 marksBitmap

A 64 GB disk has 8 KB blocks. Free-space bitmap size in KB?

Numerical answer: \_\_\_\_\_\_\_\_

**Q8**MCQ1 markFAT

A FAT has one entry for each:

1. (A) file
2. (B) directory
3. (C) disk block
4. (D) inode

### DAnswer Vault

🔐 Open the Answer Vault

**Q1** Answer: 5551 mark

5 for each group.

Re-read: [Lesson 6.1.1](#l-6-1-1) — Files, directories and access methods

**Q2** Answer: (A)1 mark

It only stores a path.

- **(B) is wrong:** Not automatically.
- **(C) is wrong:** No.
- **(D) is wrong:** The data is gone.

Re-read: [Lesson 6.1.1](#l-6-1-1) — Files, directories and access methods

**Q3** Answer: (B)1 mark

Absolute paths start at the root.

- **(A) is wrong:** That is absolute.
- **(C) is wrong:** Only if that is the current directory.
- **(D) is wrong:** No.

Re-read: [Lesson 6.1.1](#l-6-1-1) — Files, directories and access methods

**Q4** Answer: 513.01 to 513.032 marks

k = 512; (10 + 512 + 262144) × 2 KB.

Re-read: [Lesson 6.1.2](#l-6-1-2) — Allocation methods: contiguous, linked (FAT), indexed (inodes); free space

**Q5** Answer: 501 mark

Blocks 0 to 49.

Re-read: [Lesson 6.1.2](#l-6-1-2) — Allocation methods: contiguous, linked (FAT), indexed (inodes); free space

**Q6** Answer: 12351 mark

1200 + 35.

Re-read: [Lesson 6.1.2](#l-6-1-2) — Allocation methods: contiguous, linked (FAT), indexed (inodes); free space

**Q7** Answer: 10242 marks

2²³ blocks → 2²³ bits = 2²⁰ bytes.

Re-read: [Lesson 6.1.2](#l-6-1-2) — Allocation methods: contiguous, linked (FAT), indexed (inodes); free space

**Q8** Answer: (C)1 mark

Each entry gives the next block of the chain.

- **(A) is wrong:** Files are chains in the table.
- **(B) is wrong:** No.
- **(D) is wrong:** FAT systems don't use inodes.

Re-read: [Lesson 6.1.2](#l-6-1-2) — Allocation methods: contiguous, linked (FAT), indexed (inodes); free space

Type next → [**6.2.1** Disk structure and access time](#l-6-2-1)

## 📄Lesson 6.2.1 — Disk structure and access time

Phase 6 › File Systems & I/O › Chapter 6.2 Disks and I/O › Topic 6.2.1

Phase 6Ch 6.2 Disks and I/OTopic 6.2.1GATE weight: Medium≈ 40 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. Max file size with an inode? from [Lesson 6.1.2](#l-6-1-2)
2. Rights given by octal 7? from [Lesson 6.1.1](#l-6-1-1)
3. Why does a page fault take milliseconds? from [Lesson 5.3.1](#l-5-3-1)

### 1The Hook

🎣

A hard disk is a stack of spinning plates with a moving arm, like an old record player. Reading data means **moving the arm** to the right ring, **waiting for the plate to spin** the data under the head, and then **reading** it. Each step has its own time, and GATE combines them in "average access time" and "capacity" numericals.

### 2Predict First

🤔

A disk spins at 6000 rotations per minute. How long is one full rotation? On average, how long do we wait for the wanted sector to come under the head?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

6000 rpm = 100 rotations per second → **10 ms** per rotation. On average half a rotation: **5 ms**.

🗣️

In plain words

Each plate (platter) surface has rings (**tracks**) divided into **sectors**. The same ring on all surfaces forms a **cylinder**. Time to read = time to move the arm to the cylinder (**seek**) + time for the sector to arrive (**rotational latency**) + time to read the bytes (**transfer**).

#### 1. Geometry

- **Platters**, each with 2 **surfaces** and one **read/write head** per surface; all heads move together on one arm.
- **Track**: one ring on a surface. **Sector**: a slice of a track (e.g. 512 bytes). **Cylinder**: the set of tracks at the same arm position on all surfaces.
- **Capacity = surfaces × tracks per surface × sectors per track × bytes per sector.**

  16 surfaces, 1024 tracks, 256 sectors, 512 bytes → 2⁴ × 2¹⁰ × 2⁸ × 2⁹ = 2³¹ B = **2 GB**.
- Sector address (cylinder c, head h, sector s) as one number: **(c × heads + h) × sectors per track + s**.

#### 2. Access time

**Access time = seek time + rotational latency + transfer time** (+ controller overhead if given).

- **Seek time**: moving the arm; questions give an average.
- **Rotation time** = 60 / RPM seconds. **Average rotational latency = half a rotation.**

  7200 rpm → 8.33 ms per rotation → **4.17 ms** average latency.
- **Transfer time** = data size / transfer rate, or (sectors read / sectors per track) × rotation time.
- **Transfer rate** = bytes per track × rotations per second. 256 × 512 B = 128 KB per track at 120 rps → **15,360 KB/s**.

Example: 7200 rpm, average seek 6 ms, 256 sectors of 512 B per track, read 4 KB (8 sectors): 6 + 4.17 + (8/256) × 8.33 = 6 + 4.17 + 0.26 ≈ **10.43 ms**. Seek and latency dominate, so reading big contiguous chunks is far cheaper per byte.

#### 3. Solid-state drives (SSDs)

No moving parts: no seek or rotational latency, so request order matters much less. Writes wear out cells; erasure happens in large blocks.

### 4Visual

The arm moves the head to the right track (seek); the platter spins the wanted sector under it (rotational latency); then the bytes are read (transfer). The same track on every surface forms a cylinder.

### 5Worked Examples

Example 1 Easy

A disk spins at 15,000 rpm. Average rotational latency?

Solution

60/15,000 s = 4 ms per rotation → **2 ms**.

Example 2 Medium

A disk has 8 surfaces, 2048 tracks per surface, 128 sectors per track and 512-byte sectors. Capacity?

Solution

2³ × 2¹¹ × 2⁷ × 2⁹ = 2³⁰ B = **1 GB**.

Example 3 GATE

16 heads, 256 sectors per track. What is the linear sector number of (cylinder 2, head 3, sector 10)?

Solution

(2 × 16 + 3) × 256 + 10 = 35 × 256 + 10 = **8970**.

### 6GATE Traps

⚠️

- Average latency is **half** a rotation, not a full one.
- RPM is per **minute**: rotation time = 60 / RPM seconds.
- Capacity uses **surfaces** (or heads), not platters, unless told each platter is one surface.
- Seek time is usually the largest term; transfer of a few sectors is tiny.

### 7Memory Hook

🧠

**"Seek + half a turn + transfer. Capacity = surfaces × tracks × sectors × bytes."**

### 8Connect the Dots

Seek time is the part we can reduce by choosing **which request to serve next**. The next lesson compares disk-scheduling algorithms on one request queue.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**NAT1 markLatency

A disk spins at 7200 rpm. Average rotational latency in ms (2 decimals)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT1 markCapacity

16 surfaces, 1024 tracks per surface, 256 sectors per track, 512 bytes per sector. Capacity in GB?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT2 marksAccess time

7200 rpm, average seek 6 ms, 256 sectors (512 B each) per track. Average time to read one 4 KB block (2 decimals)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**NAT2 marksTransfer rate

A track holds 256 sectors of 512 bytes and the disk spins at 7200 rpm. Transfer rate in KB/s?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**NAT1 markAddressing

8 heads and 64 sectors per track. Linear sector number of (cylinder 5, head 2, sector 7)?

Numerical answer: \_\_\_\_\_\_\_\_

### 10Rule Card

- Track, sector, cylinder; one head per surface.
- Capacity = surfaces × tracks × sectors × bytes.
- Access = seek + latency + transfer; rotation = 60/RPM s; average latency = half a rotation.
- Transfer rate = bytes per track × rotations per second. Linear sector = (c × heads + h) × sectors + s.
- SSD: no seek, no rotation.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

plattersurfacetracksectorcylinderread/write headdisk capacityseek timerotational latencytransfer timetransfer rateaccess timelinear sector addressingsolid-state drive

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. (direct + k + k² + k³) × block size, k = block/pointer.
2. rwx.
3. The page must be read from disk.

#### Self-Test

**Q1** Answer: 4.16 to 4.171 mark

8.33 ms per rotation / 2.

Re-read: [Lesson 6.2.1](#l-6-2-1) — Disk structure and access time

**Q2** Answer: 21 mark

2³¹ bytes.

Re-read: [Lesson 6.2.1](#l-6-2-1) — Disk structure and access time

**Q3** Answer: 10.42 to 10.442 marks

6 + 4.17 + 0.26.

Re-read: [Lesson 6.2.1](#l-6-2-1) — Disk structure and access time

**Q4** Answer: 153602 marks

128 KB per rotation × 120 rotations per second.

Re-read: [Lesson 6.2.1](#l-6-2-1) — Disk structure and access time

**Q5** Answer: 26951 mark

(5 × 8 + 2) × 64 + 7.

Re-read: [Lesson 6.2.1](#l-6-2-1) — Disk structure and access time

Type next → [**6.2.2** Disk scheduling: FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK](#l-6-2-2)

## 📄Lesson 6.2.2 — Disk scheduling: FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK

Phase 6 › File Systems & I/O › Chapter 6.2 Disks and I/O › Topic 6.2.2

Phase 6Ch 6.2 Disks and I/OTopic 6.2.2GATE weight: High≈ 55 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. Average rotational latency? from [Lesson 6.2.1](#l-6-2-1)
2. Which part of access time can request ordering reduce? from [Lesson 6.2.1](#l-6-2-1)
3. Which CPU scheduling algorithm can starve long jobs? from [Lesson 2.1.2](#l-2-1-2)

### 1The Hook

🎣

A lift in a tall building doesn't serve floors in the order the buttons were pressed; that would send it up and down for ever. It keeps going in one direction, stopping on the way. Disk arms work the same way, and GATE asks for the **total head movement** under each algorithm almost every year. One request queue is used for the whole lesson.

### 2Predict First

🤔

The head is at cylinder 53. Requests: 98, 183, 37, 122, 14, 124, 65, 67. If we serve them in arrival order, how far does the head move in total?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

45 + 85 + 146 + 85 + 108 + 110 + 59 + 2 = **640 cylinders**.

🗣️

In plain words

Every request names a cylinder. The algorithm decides the order in which the arm visits them. Total head movement = sum of the distances travelled. Less movement means less seek time.

**Running queue** (cylinders 0–199, head at **53**): 98, 183, 37, 122, 14, 124, 65, 67.

#### 1. FCFS

Serve in arrival order. Fair, but the arm zig-zags: **640**.

#### 2. SSTF (shortest seek time first)

Always go to the **nearest** pending request: 53 → 65 → 67 → 37 → 14 → 98 → 122 → 124 → 183. 12 + 2 + 30 + 23 + 84 + 24 + 2 + 59 = **236**. Like SJF, it can **starve** far requests.

#### 3. SCAN (elevator)

Move in one direction to the **end of the disk**, serving requests on the way, then reverse.

- Moving towards 0: 53 → 37 → 14 → **0** → 65 → 67 → 98 → 122 → 124 → 183 = 53 + 183 = **236**.
- Moving towards 199: 53 → … → 183 → **199** → 37 → 14 = 146 + 185 = **331**.

#### 4. LOOK

Like SCAN, but reverse at the **last request**, not at the disk's end.

- Towards 199: 53 → … → 183 → 37 → 14 = 130 + 169 = **299**.
- Towards 0: 53 → 37 → 14 → 65 → … → 183 = 39 + 169 = **208**.

#### 5. C-SCAN (circular SCAN)

Move in one direction to the end, **jump back to the other end**, and continue in the same direction. Gives more uniform waiting times. Towards 199 (counting the return jump): 53 → … → 183 → 199 → 0 → 14 → 37 = 146 + 199 + 37 = **382**.

#### 6. C-LOOK

Like C-SCAN, but go only as far as the last request, then jump to the **farthest request at the other side**. Towards 199: 53 → … → 183 → 14 → 37 = 130 + 169 + 23 = **322**.

| Algorithm | Total movement (head 53) |
| --- | --- |
| FCFS | 640 |
| SSTF | 236 |
| SCAN towards 0 / towards 199 | 236 / 331 |
| LOOK towards 199 / towards 0 | 299 / 208 |
| C-SCAN towards 199 | 382 |
| C-LOOK towards 199 | 322 |

Convention used here: the return jump of C-SCAN/C-LOOK **is counted**. Some questions say not to count it; read carefully.

### 4Visual

```
SSTF on the running queue (cylinder scale 0 ... 199)

0    14      37         53  65 67           98       122 124              183      199
|----+-------+----------+---+--+------------+--------+---+----------------+--------|
                        53 ->65->67
             37 <------------------                       (nearest after 67 is 37)
     14 <----
     ------------------------------------> 98 --> 122 -> 124 ---------> 183
total = 12 + 2 + 30 + 23 + 84 + 24 + 2 + 59 = 236
```

### 5Worked Examples

Example 1 Easy

Head at 50, requests 40, 60, 10 (FCFS). Total movement?

Solution

10 + 20 + 50 = **80**.

Example 2 Medium

Head at 50, requests 40, 60, 10, 90 (SSTF). Order and total?

Solution

40 and 60 are both 10 away; take the lower, 40. From 40: 60 is 20 away, 10 is 30 away → 60. From 60: 90 (30) beats 10 (50). Finally 10. Order 40, 60, 90, 10: 10 + 20 + 30 + 80 = **140**.

Example 3 GATE

Running queue, head at 53, C-SCAN moving towards 199, return jump counted. Total?

Solution

146 (53 → 199) + 199 (199 → 0) + 37 (0 → 37) = **382**.

### 6GATE Traps

⚠️

- SCAN goes to the **disk's end** (0 or 199); LOOK stops at the last request.
- C-SCAN/C-LOOK serve requests in **one direction only**; check whether the return jump counts.
- SSTF ties: state the rule (here: the lower cylinder).
- Check the initial direction given in the question.

### 7Memory Hook

🧠

**"FCFS zig-zags, SSTF grabs the nearest, SCAN is a lift to the wall, LOOK turns at the last stop, C- versions only go one way."**

### 8Connect the Dots

Disk scheduling decides *which* request the disk serves. The last lesson looks at *how* data moves between devices and memory at all: polling, interrupts and **DMA**, plus buffering and spooling.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**NAT2 marksSSTF

Running queue (98, 183, 37, 122, 14, 124, 65, 67), head at 53. Total head movement with SSTF?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT2 marksSCAN

Running queue, head at 53, SCAN moving towards 199 first (cylinders 0–199). Total head movement?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT2 marksLOOK

Running queue, head at 53, LOOK moving towards 0 first. Total head movement?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**NAT2 marksC-LOOK

Running queue, head at 53, C-LOOK moving towards 199, counting the jump. Total head movement?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**MCQ1 markStarvation

Which disk-scheduling algorithm can starve a request far from the head?

1. (A) SCAN
2. (B) SSTF
3. (C) FCFS
4. (D) C-SCAN

### 10Rule Card

- FCFS: arrival order. SSTF: nearest next (starvation).
- SCAN: sweep to the disk's end, reverse. LOOK: reverse at the last request.
- C-SCAN: sweep to the end, jump to the other end, continue same direction. C-LOOK: jump from last request to the farthest one.
- Running queue (head 53): FCFS 640, SSTF 236, SCAN ↓ 236 / ↑ 331, LOOK ↑ 299 / ↓ 208, C-SCAN ↑ 382, C-LOOK ↑ 322.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

disk schedulingtotal head movementFCFSshortest seek time firstSCAN (elevator)LOOKC-SCANC-LOOKdirection of the sweepcounting the return jump

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. Half a rotation.
2. Seek time.
3. SJF/SRTF.

#### Self-Test

**Q1** Answer: 2362 marks

53 → 65 → 67 → 37 → 14 → 98 → 122 → 124 → 183.

Re-read: [Lesson 6.2.2](#l-6-2-2) — Disk scheduling: FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK

**Q2** Answer: 3312 marks

146 to the end, then 185 down to 14.

Re-read: [Lesson 6.2.2](#l-6-2-2) — Disk scheduling: FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK

**Q3** Answer: 2082 marks

39 down to 14, then 169 up to 183.

Re-read: [Lesson 6.2.2](#l-6-2-2) — Disk scheduling: FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK

**Q4** Answer: 3222 marks

130 + 169 + 23.

Re-read: [Lesson 6.2.2](#l-6-2-2) — Disk scheduling: FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK

**Q5** Answer: (B)1 mark

Nearby requests keep winning.

- **(A) is wrong:** The sweep reaches every cylinder.
- **(C) is wrong:** Serves in order.
- **(D) is wrong:** Same.

Re-read: [Lesson 6.2.2](#l-6-2-2) — Disk scheduling: FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK

Type next → [**6.2.3** I/O techniques: programmed I/O, interrupts, DMA, buffering and spooling](#l-6-2-3)

## 📄Lesson 6.2.3 — I/O techniques: programmed I/O, interrupts, DMA, buffering and spooling

Phase 6 › File Systems & I/O › Chapter 6.2 Disks and I/O › Topic 6.2.3

Phase 6Ch 6.2 Disks and I/OTopic 6.2.3GATE weight: Medium≈ 45 min

### 0Recall Warm-up

Answer from memory first. Answers are in the Answer Vault at the bottom.

1. SSTF total for the running queue? from [Lesson 6.2.2](#l-6-2-2)
2. Average rotational latency at 6000 rpm? from [Lesson 6.2.1](#l-6-2-1)
3. What is an interrupt? from [Lesson 0.1.2](#l-0-1-2)

### 1The Hook

🎣

A kettle can be watched until it boils (wasting your time), or it can whistle when ready (you do other things meanwhile). Better still, ask a helper to pour all the cups and tell you when they're done. Those are **programmed I/O**, **interrupt-driven I/O** and **DMA**. GATE asks what fraction of the CPU each one uses.

### 2Predict First

🤔

A device delivers one byte every 100 µs. Handling an interrupt costs the CPU 4 µs. If the CPU waits in a loop for each byte, it is busy 100% of the time. With interrupts, what fraction is it busy?

Make a guess in your head. The answer opens Section 3.

### 3Core Concept

💡

Predict First — the answer

4 µs out of every 100 µs = **4%**: 25 times better.

🗣️

In plain words

A **device controller** has a few registers (data, status, command). The CPU can keep checking the status register (**polling**), let the device interrupt when it's ready, or let a **DMA** controller move a whole block into memory by itself and interrupt only once at the end.

#### 1. Programmed I/O (polling)

The CPU loops reading the status register until the device is ready, then moves each byte itself. Simple, but the CPU is **busy waiting** for the whole transfer.

#### 2. Interrupt-driven I/O

The CPU starts the operation and does other work; the device **interrupts** when it has data (or finished). The CPU pays an **interrupt overhead** per transfer unit. CPU fraction used = (transfers per second) × (overhead per transfer). Example: 2,000,000 bytes/s moved as 4-byte words → 500,000 interrupts/s; at 1 µs each → **50%** of the CPU.

#### 3. Direct memory access (DMA)

- The CPU tells the DMA controller: source, destination, byte count. The DMA controller moves the whole block between device and memory and interrupts the CPU **once per block**.
- While copying, the DMA controller uses the memory bus, sometimes delaying the CPU's own memory accesses: **cycle stealing**.
- CPU cost per block = setup + one interrupt. Example: 2,000,000 B/s in 4,000-byte blocks → 500 blocks/s; at 20 µs each → **1%** of the CPU.
- Cycle-stealing fraction = (words per second) × (memory cycle time). 500,000 words/s × 100 ns = **5%**.

#### 4. Buffering, caching, spooling

- **Buffer**: memory holding data in transit (e.g. speed mismatch between a modem and a disk). **Double buffering**: fill one buffer while the other is being processed.
- **Cache**: a fast copy of data kept for reuse (not the only copy).
- **Spooling**: a queue of complete jobs for a device that can't interleave, like a printer: each print job is saved to disk and printed in turn.

#### 5. Blocking, non-blocking and asynchronous calls

- **Blocking**: the process waits until the I/O completes (simplest; the process goes to the Waiting state).
- **Non-blocking**: returns at once with whatever is available.
- **Asynchronous**: returns at once; the process is told later when the full transfer finishes.

### 4Visual

```
Who moves the data, and how often is the CPU disturbed?

Programmed I/O : CPU polls + moves every byte        CPU busy 100% of the transfer
Interrupt I/O  : device interrupts per byte/word      CPU pays overhead per unit
DMA            : DMA controller moves the block       CPU pays setup + 1 interrupt per block
                 (steals memory cycles meanwhile)
```

### 5Worked Examples

Example 1 Easy

A device produces 10,000 bytes per second, byte by byte. Interrupt overhead is 4 µs. Fraction of CPU time used in interrupt mode?

Solution

10,000 × 4 µs = 40,000 µs per second = **4%**.

Example 2 Medium

In the Easy example, how many times better is interrupt mode than programmed (polling) mode, where the CPU is busy for the whole transfer?

Solution

100% / 4% = **25** times.

Example 3 GATE

A DMA controller transfers 4-byte words at 2,000,000 bytes/s, stealing one 100 ns memory cycle per word. What percentage of memory cycles does the CPU lose?

Solution

500,000 words/s × 100 ns = 0.05 s per second = **5%**.

### 6GATE Traps

⚠️

- Interrupt cost scales with the **number of transfers**, not bytes, if each interrupt moves a word or block.
- DMA interrupts **once per block**, not per byte.
- Spooling ≠ buffering: spooling queues whole jobs for a non-sharable device.
- Units: 1 µs = 10⁻⁶ s; 1 ns = 10⁻⁹ s.

### 7Memory Hook

🧠

**"Poll = watch the kettle; interrupt = it whistles; DMA = a helper pours and tells you once."**

### 8Connect the Dots

Phase 6 is complete, and with it the whole syllabus. Phase 7 puts everything together: the master rule sheet, mixed practice, the GATE pattern drill and the final test.

### 9Self-Test

GATE format. Try every question before opening the vault.

**Q1**NAT1 markInterrupt mode

A device produces 20,000 bytes per second, byte by byte; interrupt overhead 5 µs. Percentage of CPU time used?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT2 marksGain

A device delivers 10,000 bytes per second (one at a time). Programmed I/O keeps the CPU busy for the whole transfer; interrupt overhead is 4 µs per byte. How many times better is interrupt mode?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT2 marksDMA blocks

A device transfers 2,000,000 bytes per second using DMA blocks of 4,000 bytes; each block costs the CPU 20 µs (setup and interrupt). Percentage of CPU time used?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**MCQ1 markSpooling

Several processes print at the same time, and each document comes out whole, one after another. This is achieved by:

1. (A) polling
2. (B) caching
3. (C) double buffering
4. (D) spooling

**Q5**MCQ1 markDMA

With DMA, the CPU is interrupted:

1. (A) once when the whole block has been transferred
2. (B) never
3. (C) for every word
4. (D) for every byte

### 10Rule Card

- Programmed I/O: CPU polls and moves data (busy waiting).
- Interrupt I/O: CPU fraction = transfers/s × overhead per transfer.
- DMA: one interrupt per block; cycle stealing fraction = words/s × memory cycle.
- Buffer (in transit), double buffering, cache (copy for reuse), spool (queue of jobs for a non-sharable device).
- Blocking, non-blocking, asynchronous I/O calls.

### 11Concept Ledger

Unlocked in this lesson. From here on, these terms may be used.

device controllerstatus/data/command registersprogrammed I/O (polling)interrupt-driven I/Ointerrupt overheaddirect memory accesscycle stealingbufferingdouble bufferingcachingspoolingblocking, non-blocking and asynchronous I/O

### 12Answer Vault

🔐 Open the Answer Vault

#### Recall Warm-up

1. 236.
2. 5 ms.
3. A signal from hardware that makes the CPU run a handler.

#### Self-Test

**Q1** Answer: 101 mark

20,000 × 5 µs = 0.1 s per second.

Re-read: [Lesson 6.2.3](#l-6-2-3) — I/O techniques: programmed I/O, interrupts, DMA, buffering and spooling

**Q2** Answer: 252 marks

100 µs per byte vs 4 µs.

Re-read: [Lesson 6.2.3](#l-6-2-3) — I/O techniques: programmed I/O, interrupts, DMA, buffering and spooling

**Q3** Answer: 12 marks

500 blocks × 20 µs = 10 ms per second.

Re-read: [Lesson 6.2.3](#l-6-2-3) — I/O techniques: programmed I/O, interrupts, DMA, buffering and spooling

**Q4** Answer: (D)1 mark

Jobs are queued on disk for the printer.

- **(A) is wrong:** Checking a status register.
- **(B) is wrong:** Caches copy data for reuse.
- **(C) is wrong:** Overlaps producing and consuming.

Re-read: [Lesson 6.2.3](#l-6-2-3) — I/O techniques: programmed I/O, interrupts, DMA, buffering and spooling

**Q5** Answer: (A)1 mark

The controller moves the block itself.

- **(B) is wrong:** It must learn the transfer finished.
- **(C) is wrong:** Same.
- **(D) is wrong:** That is interrupt-driven I/O.

Re-read: [Lesson 6.2.3](#l-6-2-3) — I/O techniques: programmed I/O, interrupts, DMA, buffering and spooling

Type next → [**LI-6.2** Chapter 6.2 Lock-in](#l-LI-6-2)

## 🔒Chapter 6.2 Lock-in — Disks and I/O

Phase 6 › File Systems & I/O › Chapter 6.2 Disks and I/O

Phase 6Ch 6.2 Disks and I/O

### ACompressed recap

🧾

Capacity = surfaces × tracks × sectors × bytes; access = seek + half-rotation latency + transfer; rotation = 60/RPM. Disk scheduling on the running queue (head 53): FCFS 640, SSTF 236, SCAN ↓ 236 / ↑ 331, LOOK ↑ 299 / ↓ 208, C-SCAN ↑ 382, C-LOOK ↑ 322. Programmed I/O busy-waits; interrupts cost per transfer; DMA one interrupt per block, cycle stealing; buffering, caching, spooling.

### BMerged rule card

[6.2.1](#l-6-2-1) Disk structure and access time

- Track, sector, cylinder; one head per surface.
- Capacity = surfaces × tracks × sectors × bytes.
- Access = seek + latency + transfer; rotation = 60/RPM s; average latency = half a rotation.
- Transfer rate = bytes per track × rotations per second. Linear sector = (c × heads + h) × sectors + s.
- SSD: no seek, no rotation.

[6.2.2](#l-6-2-2) Disk scheduling: FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK

- FCFS: arrival order. SSTF: nearest next (starvation).
- SCAN: sweep to the disk's end, reverse. LOOK: reverse at the last request.
- C-SCAN: sweep to the end, jump to the other end, continue same direction. C-LOOK: jump from last request to the farthest one.
- Running queue (head 53): FCFS 640, SSTF 236, SCAN ↓ 236 / ↑ 331, LOOK ↑ 299 / ↓ 208, C-SCAN ↑ 382, C-LOOK ↑ 322.

[6.2.3](#l-6-2-3) I/O techniques: programmed I/O, interrupts, DMA, buffering and spooling

- Programmed I/O: CPU polls and moves data (busy waiting).
- Interrupt I/O: CPU fraction = transfers/s × overhead per transfer.
- DMA: one interrupt per block; cycle stealing fraction = words/s × memory cycle.
- Buffer (in transit), double buffering, cache (copy for reuse), spool (queue of jobs for a non-sharable device).
- Blocking, non-blocking, asynchronous I/O calls.

### CInterleaved GATE-style questions

**Q1**NAT1 markLatency

A disk spins at 6000 rpm. Average rotational latency in ms?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT2 marksCapacity

4 platters with 2 surfaces each, 4096 tracks per surface, 64 sectors per track, 512 bytes per sector. Capacity in GB?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT2 marksFCFS

Head at 100; requests 23, 89, 132, 42, 187 served FCFS. Total head movement?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**NAT2 marksSSTF

Head at 100; requests 23, 89, 132, 42, 187 (SSTF). Total head movement?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**NAT2 marksSCAN

Head at 100 moving towards 199 (cylinders 0–199); requests 23, 89, 132, 42, 187 (SCAN). Total head movement?

Numerical answer: \_\_\_\_\_\_\_\_

**Q6**MCQ1 markC-SCAN

The main advantage of C-SCAN over SCAN is:

1. (A) less total movement always
2. (B) more uniform waiting time across cylinders
3. (C) no need to know the head direction
4. (D) it serves the nearest request first

**Q7**NAT1 markInterrupts

A device sends 100,000 words per second, one interrupt per word, 2 µs per interrupt. Percentage of CPU time used?

Numerical answer: \_\_\_\_\_\_\_\_

**Q8**MCQ1 markDMA

Cycle stealing refers to:

1. (A) interrupts being lost
2. (B) the disk skipping sectors
3. (C) the DMA controller using memory cycles that delay the CPU
4. (D) the CPU taking time slices from processes

### DAnswer Vault

🔐 Open the Answer Vault

**Q1** Answer: 51 mark

10 ms per rotation / 2.

Re-read: [Lesson 6.2.1](#l-6-2-1) — Disk structure and access time

**Q2** Answer: 12 marks

8 × 2¹² × 2⁶ × 2⁹ = 2³⁰.

Re-read: [Lesson 6.2.1](#l-6-2-1) — Disk structure and access time

**Q3** Answer: 4212 marks

77 + 66 + 43 + 90 + 145.

Re-read: [Lesson 6.2.2](#l-6-2-2) — Disk scheduling: FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK

**Q4** Answer: 2732 marks

100 → 89 → 132 → 187 → 42 → 23.

Re-read: [Lesson 6.2.2](#l-6-2-2) — Disk scheduling: FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK

**Q5** Answer: 2752 marks

99 up to 199, then 176 down to 23.

Re-read: [Lesson 6.2.2](#l-6-2-2) — Disk scheduling: FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK

**Q6** Answer: (B)1 mark

Every cylinder is reached at regular intervals.

- **(A) is wrong:** Not always less.
- **(C) is wrong:** It sweeps one way.
- **(D) is wrong:** That is SSTF.

Re-read: [Lesson 6.2.2](#l-6-2-2) — Disk scheduling: FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK

**Q7** Answer: 201 mark

0.2 s per second.

Re-read: [Lesson 6.2.3](#l-6-2-3) — I/O techniques: programmed I/O, interrupts, DMA, buffering and spooling

**Q8** Answer: (C)1 mark

Both share the memory bus.

- **(A) is wrong:** No.
- **(B) is wrong:** No.
- **(D) is wrong:** That is pre-emption.

Re-read: [Lesson 6.2.3](#l-6-2-3) — I/O techniques: programmed I/O, interrupts, DMA, buffering and spooling

Type next → [**CP-6** Phase 6 Checkpoint (15 questions)](#l-CP-6)

## ⏱️Phase 6 Checkpoint — File Systems & I/O

Phase 6 › File Systems & I/O

Phase 6

Phase 6 Checkpoint: 15 questions on file systems and I/O.

⏱️

**15 questions · 23 marks · 45 minutes.** Negative marking on MCQ only: −1/3 mark for a wrong 1-mark MCQ, −2/3 for a wrong 2-mark MCQ. No negative marking for MSQ or NAT; MSQ has no partial credit.

**Q1**NAT1 markPermissions

Octal value of `rwxrw-r--`?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**MCQ1 markHard links

A file has link count 3. Two of its names are deleted. The data is:

1. (A) freed
2. (B) turned into a symbolic link
3. (C) moved to the root directory
4. (D) still there (link count 1)

**Q3**MCQ1 markTables

The open count of a file is kept in:

1. (A) the system-wide open-file table
2. (B) the per-process open-file table
3. (C) the boot block
4. (D) the free-space bitmap

**Q4**NAT2 marksInode

Inode with 12 direct pointers and one single, one double and one triple indirect pointer; blocks 1 KB; pointers 4 bytes. Maximum file size in GB (2 decimals)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**NAT2 marksInode reads

Inode with 12 direct pointers, 4 KB blocks, 4-byte pointers; inode in memory. Disk reads needed to read file block 2441?

Numerical answer: \_\_\_\_\_\_\_\_

**Q6**NAT2 marksFAT

A 1 TB disk uses 4 KB blocks. At least how many bits must a FAT entry have to number every block?

Numerical answer: \_\_\_\_\_\_\_\_

**Q7**MCQ1 markLinked allocation

The main weakness of linked allocation without a FAT is:

1. (A) it needs an index block
2. (B) slow direct access
3. (C) external fragmentation
4. (D) files cannot grow

**Q8**NAT1 markRotation

A disk spins at 5400 rpm. Average rotational latency in ms (2 decimals)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q9**NAT2 marksAccess time

Average seek 5 ms, 6000 rpm, 100 sectors per track. Average time to read 10 consecutive sectors in ms?

Numerical answer: \_\_\_\_\_\_\_\_

**Q10**NAT2 marksFCFS

Running queue (98, 183, 37, 122, 14, 124, 65, 67), head 53, FCFS. Total head movement?

Numerical answer: \_\_\_\_\_\_\_\_

**Q11**NAT2 marksSCAN

Running queue, head 53, SCAN towards 0 first. Total head movement?

Numerical answer: \_\_\_\_\_\_\_\_

**Q12**NAT2 marksC-SCAN

Running queue, head 53, C-SCAN towards 199, counting the return jump. Total head movement?

Numerical answer: \_\_\_\_\_\_\_\_

**Q13**MCQ1 markLOOK

LOOK differs from SCAN in that it:

1. (A) moves in one direction only
2. (B) serves the nearest request first
3. (C) reverses at the last request instead of the disk's end
4. (D) ignores new requests

**Q14**NAT2 marksDMA

A DMA device moves 8-byte words at 4,000,000 bytes per second, stealing one 50 ns memory cycle per word. Percentage of memory cycles lost by the CPU (2 decimals)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q15**MCQ1 markBuffering

Double buffering lets:

1. (A) two processes print at once
2. (B) data be cached forever
3. (C) the disk avoid seeks
4. (D) one buffer be filled while the other is processed

### ✓Answer Vault

🔐 Open the Answer Vault

**Q1** Answer: 7641 mark

7, 6, 4.

Re-read: [Lesson 6.1.1](#l-6-1-1) — Files, directories and access methods

**Q2** Answer: (D)1 mark

Freed only at count 0.

- **(A) is wrong:** One name remains.
- **(B) is wrong:** No.
- **(C) is wrong:** No.

Re-read: [Lesson 6.1.1](#l-6-1-1) — Files, directories and access methods

**Q3** Answer: (A)1 mark

It counts opens across processes.

- **(B) is wrong:** That holds the file pointer.
- **(C) is wrong:** Unrelated.
- **(D) is wrong:** Unrelated.

Re-read: [Lesson 6.1.1](#l-6-1-1) — Files, directories and access methods

**Q4** Answer: 16.06 to 16.072 marks

k = 256; (12 + 256 + 65536 + 16777216) KB.

Re-read: [Lesson 6.1.2](#l-6-1-2) — Allocation methods: contiguous, linked (FAT), indexed (inodes); free space

**Q5** Answer: 32 marks

Double-indirect range (1036 onward).

Re-read: [Lesson 6.1.2](#l-6-1-2) — Allocation methods: contiguous, linked (FAT), indexed (inodes); free space

**Q6** Answer: 282 marks

2⁴⁰ / 2¹² = 2²⁸ blocks.

Re-read: [Lesson 6.1.2](#l-6-1-2) — Allocation methods: contiguous, linked (FAT), indexed (inodes); free space

**Q7** Answer: (B)1 mark

Must follow pointers.

- **(A) is wrong:** That is indexed allocation.
- **(C) is wrong:** None.
- **(D) is wrong:** Growth is easy.

Re-read: [Lesson 6.1.2](#l-6-1-2) — Allocation methods: contiguous, linked (FAT), indexed (inodes); free space

**Q8** Answer: 5.55 to 5.561 mark

11.11 ms per rotation / 2.

Re-read: [Lesson 6.2.1](#l-6-2-1) — Disk structure and access time

**Q9** Answer: 112 marks

5 + 5 + (10/100) × 10.

Re-read: [Lesson 6.2.1](#l-6-2-1) — Disk structure and access time

**Q10** Answer: 6402 marks

Arrival order.

Re-read: [Lesson 6.2.2](#l-6-2-2) — Disk scheduling: FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK

**Q11** Answer: 2362 marks

53 down to 0, then 183 up.

Re-read: [Lesson 6.2.2](#l-6-2-2) — Disk scheduling: FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK

**Q12** Answer: 3822 marks

146 + 199 + 37.

Re-read: [Lesson 6.2.2](#l-6-2-2) — Disk scheduling: FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK

**Q13** Answer: (C)1 mark

No trip to the edge.

- **(A) is wrong:** That is C-SCAN.
- **(B) is wrong:** That is SSTF.
- **(D) is wrong:** No.

Re-read: [Lesson 6.2.2](#l-6-2-2) — Disk scheduling: FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK

**Q14** Answer: 2.52 marks

500,000 words × 50 ns = 0.025 s per second.

Re-read: [Lesson 6.2.3](#l-6-2-3) — I/O techniques: programmed I/O, interrupts, DMA, buffering and spooling

**Q15** Answer: (D)1 mark

Producer and consumer overlap.

- **(A) is wrong:** That is spooling's job.
- **(B) is wrong:** No.
- **(C) is wrong:** No.

Re-read: [Lesson 6.2.3](#l-6-2-3) — I/O techniques: programmed I/O, interrupts, DMA, buffering and spooling

Type next → [**7.1.1** Master Rule Sheet (all rule cards merged)](#l-7-1-1)

# 🏁Phase 7 — Integration & Final Test

## 🔁7.1.1 — Master Rule Sheet (all rule cards merged)

Phase 7 › Integration & Final Test › Chapter 7.1 Master rule sheet

Phase 7Ch 7.1 Master rule sheet≈ 60 min

Every Rule Card from the 33 lessons, grouped by phase, in course order. Use it for revision in the last weeks: read one phase per sitting, and for any line you cannot explain in your own words, open its lesson (the lesson ID links to it).

📝

How to revise with this sheet

1. Cover the rules of a lesson with your hand; say them from its title alone.
2. Check, and mark the lesson's ID on paper if you missed anything.
3. Next day, re-test only the marked IDs (spaced recall).

#### 🧭 Phase 0 · Foundations from Zero

[0.1.1](#l-0-1-1) Inside a computer: CPU, memory, disk, I/O; bits, bytes and powers of two

- CPU executes, RAM holds current work (volatile), disk stores permanently, I/O connects the outside.
- Program = file; process = program in execution.
- Byte = 8 bits; n bits → 2ⁿ values; 1 KB = 2¹⁰, 1 MB = 2²⁰, 1 GB = 2³⁰.
- 2ⁿ bytes ↔ n address bits; divide powers of two by subtracting exponents.

[0.1.2](#l-0-1-2) What an operating system does: kernel, user mode and kernel mode, interrupts

- OS = resource manager + abstraction + protection; kernel runs in kernel mode.
- Mode bit: user mode (restricted) vs kernel mode (all instructions).
- Privileged: I/O, set timer, enable/disable interrupts, memory-management registers, halt. Not privileged: arithmetic, read clock, trap/system-call instruction.
- Interrupt = from hardware; trap/exception = from the running program; timer interrupt returns control to the OS.
- Multiprogramming keeps the CPU busy; time-sharing switches fast for interaction.

[0.1.3](#l-0-1-3) System calls: how programs ask the operating system for help

- System call: wrapper → parameters + number → trap → kernel handler via system-call table → result → return to user mode (2 mode switches).
- Parameters: registers, memory block, or stack.
- Categories: process (fork, exec, exit, wait), file (open, read, write, close, lseek), device, information, communication.
- printf, malloc, strlen are library functions; write, brk are system calls.
- Monolithic kernel vs microkernel.

#### ⚙️ Phase 1 · Processes & Threads

[1.1.1](#l-1-1-1) Processes: memory layout, process control block and process states

- Process memory: text (code), data (globals), heap (dynamic, grows up), stack (calls, grows down).
- PCB: PID, state, program counter, registers, scheduling info, memory info, open files, accounting.
- States: New, Ready, Running, Waiting, Terminated.
- Transitions: admit, dispatch (Ready→Running), pre-empt (Running→Ready), I/O request (Running→Waiting), event done (Waiting→Ready), exit. Waiting→Running and Ready→Waiting are impossible.
- Suspended-ready / suspended-waiting via swapping.

[1.1.2](#l-1-1-2) Creating processes with fork(), exec() and wait(); context switches and schedulers

- fork: child is a copy; returns 0 in child, child PID in parent; memory is copied, not shared.
- n sequential forks → 2ⁿ processes, 2ⁿ − 1 children; prints after forks happen once per process; inside a loop, add per iteration.
- exec replaces the program; wait waits for a child; zombie = exited, not waited for; orphan = parent gone.
- Context switch = save + load PCB (overhead).
- Long-term (admission, degree of multiprogramming), short-term (CPU), medium-term (swapping).

[1.2.1](#l-1-2-1) Threads: what they share, user-level vs kernel-level threads

- Thread = path of execution inside a process; shares code, data, heap, open files; private stack, registers, PC, thread ID.
- Threads are cheaper to create and switch than processes.
- User-level: fast, kernel unaware, one block blocks all, no parallelism. Kernel-level: kernel-scheduled, independent blocking, parallel on multiple cores.
- Models: many-to-one, one-to-one, many-to-many.

[1.2.2](#l-1-2-2) Inter-process communication: shared memory, message passing and pipes

- Shared memory: map a common region; fast; programmer synchronizes.
- Message passing: send/receive via the kernel; direct or indirect (mailbox); blocking or non-blocking; works across machines; copies data.
- Ordinary pipe: one-way, parent–child; named pipe (FIFO) for unrelated processes; two-way needs two pipes.
- Producer waits when the buffer is full; consumer waits when empty.

#### ⏱️ Phase 2 · CPU Scheduling

[2.1.1](#l-2-1-1) Scheduling basics: the times we measure; first-come first-served

- AT, BT given; CT from the Gantt chart; TAT = CT − AT; WT = TAT − BT; RT = first start − AT.
- Non-pre-emptive: keep the CPU till done; pre-emptive: can be interrupted.
- FCFS: arrival order, non-pre-emptive, convoy effect; idle gaps when nothing has arrived.

[2.1.2](#l-2-1-2) Shortest job first and shortest remaining time first

- SJF: when free, pick the smallest burst; non-pre-emptive; optimal average WT.
- SRTF: at each arrival/completion, run the smallest remaining time; pre-emptive; optimal among pre-emptive.
- Both can starve long jobs; bursts predicted by τₙ₊₁ = αtₙ + (1 − α)τₙ.

[2.1.3](#l-2-1-3) Priority scheduling, starvation and aging; highest response ratio next

- Priority: pick the most important ready process (state the direction of numbers); non-pre-emptive or pre-emptive.
- Starvation of low priorities; aging raises priority over time.
- HRRN: non-pre-emptive; pick the largest (W + S)/S; no starvation.
- SJF = priority by burst length.

[2.2.1](#l-2-2-1) Round robin and the time quantum

- RR: FIFO ready queue; run min(q, remaining); unfinished → back; arrivals at the same instant queue before the pre-empted process.
- Large q → FCFS; small q → overhead; useful fraction q/(q + s); max wait between turns (n − 1)q.
- RR: worse average WT than SJF, better response time.
- Context switches: count changes between different processes.

[2.2.2](#l-2-2-2) Multilevel queues, CPU and I/O bursts, CPU utilisation

- Multilevel queue: fixed classes, fixed priority or time-sliced between queues; no movement.
- MLFQ: start at the top; full quantum used → demote; aging → promote; defined by queues, algorithms, move rules.
- CPU/I/O bursts: only CPU bursts compete; I/O overlaps; count idle at the start and end.
- Utilisation ≈ 1 − pⁿ.

#### 🔒 Phase 3 · Concurrency & Synchronization

[3.1.1](#l-3-1-1) Race conditions and the critical-section problem

- `x++` = load, add, store; a pre-emption can fall between them.
- Race condition: the result depends on timing. Lost update: both load before either stores; the last store wins.
- Structure: entry section, CS, exit section, remainder section.
- Requirements: mutual exclusion, progress, bounded waiting; no assumptions about speed.
- `x++` in two loops of n ≥ 2 each from 0: minimum 2, maximum 2n.

[3.1.2](#l-3-1-2) Software solutions: turn and flag attempts, Peterson's algorithm

- Lock variable: fails mutual exclusion.
- Strict alternation (turn): mutual exclusion ✓, progress ✗.
- Two flags: mutual exclusion ✓, progress ✗ (deadlock).
- Peterson: flag\[i\] = true; turn = j; wait while (flag\[j\] && turn == j). All three ✓, 2 processes, busy waiting.
- Swapping Peterson's first two lines breaks mutual exclusion.

[3.1.3](#l-3-1-3) Hardware help: test-and-set, compare-and-swap, spinlocks

- Atomic instruction: finishes before anything else touches that memory.
- TSL: return old, set true; lock = spin until old is false. ME ✓, progress ✓, bounded waiting ✗.
- CAS(&v, e, n): if v == e then v = n; returns the old value. Swap exchanges atomically.
- Spinlocks: good on multiprocessors for short sections; no context switch.
- Disabling interrupts: one CPU, kernel only. Priority inversion → priority inheritance.

[3.2.1](#l-3-2-1) Semaphores: wait, signal, counting and binary semaphores

- wait/P: S--; if S \< 0 block. signal/V: S++; if S ≤ 0 wake one. Atomic.
- Negative value −k = k processes waiting. Final value = initial − waits + signals.
- Binary (mutex, starts 1) vs counting (starts k). Ordering semaphore starts 0.
- Opposite orders of waits can deadlock; LIFO queues can starve.

[3.2.2](#l-3-2-2) Classic problems: bounded buffer, readers–writers, dining philosophers

- Bounded buffer: mutex = 1, empty = N, full = 0; counting wait before mutex wait; signals in any order.
- Readers–writers (reader priority): first reader waits on rw, last reader signals rw; writers may starve.
- Dining philosophers: all left-first → deadlock; fixes: ≤ 4 at table, asymmetry, both-at-once. Max ⌊n/2⌋ eat together.

[3.2.3](#l-3-2-3) Monitors, and reasoning about concurrent code

- Monitor: shared data + functions; one process active inside; condition variables wait/signal.
- x.wait releases the monitor; x.signal wakes one, or does nothing if none waits.
- Signal-and-wait vs signal-and-continue (re-check with while).
- Code analysis: shared/local → split → extremes → semaphore values → ME, deadlock, progress, starvation.

#### 🧱 Phase 4 · Deadlock

[4.1.1](#l-4-1-1) Deadlock: the four conditions and resource-allocation graphs

- Deadlock: each process in a set waits for something only another in the set can give.
- Four necessary conditions: mutual exclusion, hold and wait, no pre-emption, circular wait.
- RAG: request P → R, assignment R → P. No cycle → no deadlock; cycle + single instances → deadlock; cycle + multiple instances → maybe.
- Starvation ≠ deadlock.

[4.1.2](#l-4-1-2) Prevention and avoidance: safe states and the banker's algorithm

- Prevention breaks a condition: all-at-once requests (hold and wait), pre-emption, resource ordering (circular wait).
- Safe state: some order lets everyone finish. Unsafe ≠ deadlock.
- Banker's: Need = Max − Allocation; Work = Available; pick Need ≤ Work; Work += Allocation; all finish → safe.
- Request: ≤ Need, ≤ Available, pretend, check safety; grant only if safe.

[4.1.3](#l-4-1-3) Detection, recovery, and the minimum-resources formula

- Strategies: prevention, avoidance, detection + recovery, ignore (ostrich).
- Single instances: wait-for graph cycle = deadlock. Multiple: matrix detection with Request ≤ Work.
- Recovery: kill all / one at a time; pre-empt with victim + rollback (avoid starving one victim).
- No deadlock ⟺ R ≥ Σ(kᵢ − 1) + 1; n equal processes: R ≥ n(k − 1) + 1.

#### 🧠 Phase 5 · Memory Management & Virtual Memory

[5.1.1](#l-5-1-1) Addresses and contiguous allocation: fits and fragmentation

- Logical address from the CPU; MMU makes the physical address.
- Base/limit: if L \< limit then physical = base + L, else trap.
- Fixed partitions → internal fragmentation; variable → external; compaction merges holes.
- First fit (first big enough), next fit (continue from last), best fit (smallest big enough), worst fit (largest).
- 50% rule: N blocks allocated → about 0.5N lost (one third).

[5.2.1](#l-5-2-1) Paging: pages, frames, page tables and the address split

- Page = frame size = 2ᵈ; offset = low d bits; page number = high m − d bits.
- Physical = frame × page size + offset.
- Page-table size = (#pages) × (PTE size); frame bits = physical bits − d.
- PTE: frame, valid, protection, dirty, referenced. Shared code → same frames.
- Paging: internal fragmentation only (≈ half a page per process).

[5.2.2](#l-5-2-2) TLBs, effective access time and multilevel page tables

- EAT = h(t + m) + (1 − h)(t + 2m); with k levels the miss costs t + (k + 1)m.
- TLB: small associative cache; flush on switch unless ASIDs.
- Multilevel: entries per page = page size / PTE; bits per level = log₂ of it; levels = ⌈(m − d) / bits per level⌉.
- Inverted table: one entry per frame, searched via hashing.

[5.2.3](#l-5-2-3) Segmentation, and segmentation with paging

- Segment table entry (base, limit); (s, d) → base + d if d \< limit, else trap.
- Paging: equal pieces, internal fragmentation. Segmentation: logical pieces, external fragmentation, natural sharing/protection.
- Segmentation with paging: (s, p, d); each segment paged.

[5.3.1](#l-5-3-1) Demand paging, page faults and effective access time

- Demand paging: load on first reference; valid bit = in memory.
- Page fault: trap → check → free frame (or victim) → disk read → update table → restart.
- EAT = (1 − p)·ma + p·s; ms = 10⁶ ns.
- Dirty victims must be written back; average s weighted by the dirty fraction.
- Copy-on-write makes fork() cheap.

[5.3.2](#l-5-3-2) Page replacement: FIFO, optimal and LRU; Belady's anomaly

- FIFO: evict earliest loaded. OPT: evict farthest next use (never used = best). LRU: evict least recently used.
- Running string, 3 frames: FIFO 10, OPT 7, LRU 9; 4 frames: FIFO 7, OPT 6, LRU 6.
- Belady (FIFO): 1 2 3 4 1 2 5 1 2 3 4 5 → 9 faults with 3 frames, 10 with 4. LRU and OPT are stack algorithms (no anomaly).
- Faults ≥ distinct pages (from empty); exact LRU needs counters or a stack.

[5.3.3](#l-5-3-3) Frame allocation, thrashing, working sets and the clock algorithm

- Equal: m/n. Proportional: aᵢ = sᵢ/S × m. Global vs local replacement.
- Thrashing: more paging than work; cure by reducing multiprogramming.
- Working set: distinct pages in last Δ references; D = Σ WSS > m → suspend someone. PFF bounds.
- Clock: bit 1 → clear and move; bit 0 → replace (new page bit 1). Enhanced: prefer (0,0).

#### 💾 Phase 6 · File Systems & I/O

[6.1.1](#l-6-1-1) Files, directories and access methods

- File: attributes + operations; open() returns a descriptor; seek moves the pointer.
- System-wide table (open count) + per-process table (file pointer).
- Access: sequential, direct, indexed. Directories: single, two-level, tree (absolute/relative paths), acyclic graph, general graph.
- Hard link = same inode, link count; soft link = path (can dangle).
- UNIX rwx bits: owner/group/others, r4 w2 x1 (e.g. 754 = rwxr-xr--).

[6.1.2](#l-6-1-2) Allocation methods: contiguous, linked (FAT), indexed (inodes); free space

- Contiguous: (start, length), block b = start + b; external fragmentation.
- Linked: next pointers; block b needs b + 1 reads. FAT = one entry per disk block, cached.
- Indexed/inode: k = B/P; max size = (direct + k + k² + k³) × B; reads: direct 1, single 2, double 3, triple 4.
- Free space: bitmap (blocks/8 bytes), linked list, grouping, counting.

[6.2.1](#l-6-2-1) Disk structure and access time

- Track, sector, cylinder; one head per surface.
- Capacity = surfaces × tracks × sectors × bytes.
- Access = seek + latency + transfer; rotation = 60/RPM s; average latency = half a rotation.
- Transfer rate = bytes per track × rotations per second. Linear sector = (c × heads + h) × sectors + s.
- SSD: no seek, no rotation.

[6.2.2](#l-6-2-2) Disk scheduling: FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK

- FCFS: arrival order. SSTF: nearest next (starvation).
- SCAN: sweep to the disk's end, reverse. LOOK: reverse at the last request.
- C-SCAN: sweep to the end, jump to the other end, continue same direction. C-LOOK: jump from last request to the farthest one.
- Running queue (head 53): FCFS 640, SSTF 236, SCAN ↓ 236 / ↑ 331, LOOK ↑ 299 / ↓ 208, C-SCAN ↑ 382, C-LOOK ↑ 322.

[6.2.3](#l-6-2-3) I/O techniques: programmed I/O, interrupts, DMA, buffering and spooling

- Programmed I/O: CPU polls and moves data (busy waiting).
- Interrupt I/O: CPU fraction = transfers/s × overhead per transfer.
- DMA: one interrupt per block; cycle stealing fraction = words/s × memory cycle.
- Buffer (in transit), double buffering, cache (copy for reuse), spool (queue of jobs for a non-sharable device).
- Blocking, non-blocking, asynchronous I/O calls.

Type next → [**7.2.1** Mixed practice set 1](#l-7-2-1)

## 🔁7.2.1 — Mixed practice set 1

Phase 7 › Integration & Final Test › Chapter 7.2 Mixed practice

Phase 7Ch 7.2 Mixed practice≈ 40 min

Twelve questions from all phases, mixed on purpose so you must first recognise **which** idea each needs. Conventions as in the front matter (times in ms, KB = 2¹⁰ bytes, ties to the earlier arrival).

⏱️

**12 questions · 20 marks · 40 minutes.** Negative marking on MCQ only: −1/3 mark for a wrong 1-mark MCQ, −2/3 for a wrong 2-mark MCQ. No negative marking for MSQ or NAT; MSQ has no partial credit.

**Q1**NAT1 markAddress bits

How many address bits are needed for 512 MB of byte-addressable memory?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**MCQ1 markPrivileged instructions

Which instruction must be privileged (kernel mode only)?

1. (A) Change the page-table base register
2. (B) Execute a trap to make a system call
3. (C) Add two registers
4. (D) Load a value from memory into a register

**Q3**NAT2 marksfork()

How many characters in total does this print? `fork(); fork(); printf("A"); fork(); printf("B");`

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**MCQ1 markThreads

Which of these is NOT shared by the threads of one process?

1. (A) Global variables
2. (B) The stack
3. (C) Open files
4. (D) The heap

**Q5**NAT2 marksSRTF

P1 (arrival 0, burst 6), P2 (1, 3), P3 (2, 1), P4 (3, 4). SRTF: average waiting time?

Numerical answer: \_\_\_\_\_\_\_\_

**Q6**NAT2 marksRound robin

Same processes (P1 0/6, P2 1/3, P3 2/1, P4 3/4), RR with quantum 2. Completion time of P1?

Numerical answer: \_\_\_\_\_\_\_\_

**Q7**NAT2 marksRace

`x = 1`. Thread 1 runs `x = x * 3`, thread 2 runs `x = x + 2`, each as load/compute/store. How many different final values are possible?

Numerical answer: \_\_\_\_\_\_\_\_

**Q8**MCQ2 marksBounded buffer

A bounded buffer has 5 slots (empty = 5, full = 0 at first). The producer has added 7 items and the consumer removed 3, and nobody is waiting. Values of (empty, full)?

1. (A) (2, 3)
2. (B) (5, 0)
3. (C) (1, 4)
4. (D) (4, 1)

**Q9**NAT2 marksBanker's

11 units of one resource. A holds 3 (max 7), B holds 4 (max 6), C holds 2 (max 5). How many units are free right after the first process of a safe sequence finishes?

Numerical answer: \_\_\_\_\_\_\_\_

**Q10**NAT1 markMinimum resources

6 processes each need at most 3 units of one resource. Minimum number of units that rules out deadlock?

Numerical answer: \_\_\_\_\_\_\_\_

**Q11**NAT2 marksLRU

Reference string 1 2 3 2 4 1 5 2 1 2 3 4, 4 empty frames, LRU. Number of page faults?

Numerical answer: \_\_\_\_\_\_\_\_

**Q12**NAT2 marksSSTF

Head at 80; requests 45, 130, 10, 175, 90, 60, 150 (SSTF). Total head movement?

Numerical answer: \_\_\_\_\_\_\_\_

### ✓Answer Vault

🔐 Open the Answer Vault

**Q1** Answer: 291 mark

512 MB = 2⁹ × 2²⁰ = 2²⁹ bytes.

Re-read: [Lesson 0.1.1](#l-0-1-1) — Inside a computer: CPU, memory, disk, I/O; bits, bytes and powers of two

**Q2** Answer: (A)1 mark

It controls memory protection for every process.

- **(B) is wrong:** The trap is how user programs enter the kernel.
- **(C) is wrong:** Ordinary user instruction.
- **(D) is wrong:** Ordinary user instruction.

Re-read: [Lesson 0.1.2](#l-0-1-2) — What an operating system does: kernel, user mode and kernel mode, interrupts

**Q3** Answer: 122 marks

4 processes print A; each forks, so 8 print B.

Re-read: [Lesson 1.1.2](#l-1-1-2) — Creating processes with fork(), exec() and wait(); context switches and schedulers

**Q4** Answer: (B)1 mark

Each thread has its own stack, registers and program counter.

- **(A) is wrong:** Shared.
- **(C) is wrong:** Shared.
- **(D) is wrong:** Shared.

Re-read: [Lesson 1.2.1](#l-1-2-1) — Threads: what they share, user-level vs kernel-level threads

**Q5** Answer: 2.752 marks

P1 0–1, P2 1–2, P3 2–3, P2 3–5, P4 5–9, P1 9–14: waits 8, 1, 0, 2.

Re-read: [Lesson 2.1.2](#l-2-1-2) — Shortest job first and shortest remaining time first

**Q6** Answer: 122 marks

P1 0–2, P2 2–4, P3 4–5, P1 5–7, P4 7–9, P2 9–10, P1 10–12, P4 12–14.

Re-read: [Lesson 2.2.1](#l-2-2-1) — Round robin and the time quantum

**Q7** Answer: 32 marks

5 and 9 (one after the other) and 3 (both read 1).

Re-read: [Lesson 3.1.1](#l-3-1-1) — Race conditions and the critical-section problem

**Q8** Answer: (C)2 marks

empty = 5 − 7 + 3; full = 7 − 3.

- **(A) is wrong:** Miscounted.
- **(B) is wrong:** The initial values.
- **(D) is wrong:** Swapped.

Re-read: [Lesson 3.2.2](#l-3-2-2) — Classic problems: bounded buffer, readers–writers, dining philosophers

**Q9** Answer: 62 marks

Free 2; only B (needs 2) can finish first and returns its 4.

Re-read: [Lesson 4.1.2](#l-4-1-2) — Prevention and avoidance: safe states and the banker's algorithm

**Q10** Answer: 131 mark

6 × 2 + 1.

Re-read: [Lesson 4.1.3](#l-4-1-3) — Detection, recovery, and the minimum-resources formula

**Q11** Answer: 72 marks

1, 2, 3, 4 load; 5 evicts 3; 3 evicts 4; 4 evicts 5.

Re-read: [Lesson 5.3.2](#l-5-3-2) — Page replacement: FIFO, optimal and LRU; Belady's anomaly

**Q12** Answer: 2552 marks

80 → 90 → 60 → 45 → 10 → 130 → 150 → 175.

Re-read: [Lesson 6.2.2](#l-6-2-2) — Disk scheduling: FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK

Type next → [**7.2.2** Mixed practice set 2](#l-7-2-2)

## 🔁7.2.2 — Mixed practice set 2

Phase 7 › Integration & Final Test › Chapter 7.2 Mixed practice

Phase 7Ch 7.2 Mixed practice≈ 40 min

Twelve more mixed questions. Before computing, name the lesson each one comes from.

⏱️

**12 questions · 20 marks · 40 minutes.** Negative marking on MCQ only: −1/3 mark for a wrong 1-mark MCQ, −2/3 for a wrong 2-mark MCQ. No negative marking for MSQ or NAT; MSQ has no partial credit.

**Q1**MCQ1 markSystem calls

Which of these is a system call (not just a library function)?

1. (A) sqrt()
2. (B) toupper()
3. (C) strlen()
4. (D) read()

**Q2**MCQ1 markProcess states

Which state change can never happen directly?

1. (A) Ready → Waiting
2. (B) Waiting → Ready
3. (C) Running → Ready
4. (D) Running → Waiting

**Q3**NAT2 marksPriority

P1 (arrival 0, burst 5, priority 2), P2 (1, 3, 1), P3 (2, 8, 4), P4 (3, 2, 3); smaller number = higher priority. Non-pre-emptive priority: average waiting time?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**NAT2 marksHRRN

Same processes under HRRN. At time 5 P1 finishes. Largest response ratio among the waiting processes (2 decimals)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**NAT2 marksUtilisation

4 processes each wait for I/O half of the time (independently). CPU utilisation?

Numerical answer: \_\_\_\_\_\_\_\_

**Q6**MCQ1 markPeterson

In Peterson's solution, process i wants to enter and process j is not interested (flag\[j\] = false). What happens?

1. (A) i enters only if turn == i
2. (B) i enters immediately
3. (C) i waits until j takes a turn
4. (D) i waits for ever

**Q7**NAT1 markSemaphore

A semaphore starts at 5. Then 12 wait and 9 signal operations are performed. Final value?

Numerical answer: \_\_\_\_\_\_\_\_

**Q8**NAT2 marksDetection

Available (0, 0, 0). Allocation: P0 (1,0,1), P1 (0,1,0), P2 (1,1,0), P3 (0,0,1). Request: P0 (0,1,0), P1 (1,0,0), P2 (0,0,1), P3 (1,0,0). How many processes are deadlocked?

Numerical answer: \_\_\_\_\_\_\_\_

**Q9**NAT2 marksTLB

Memory access 120 ns, TLB 10 ns, hit ratio 0.9, single-level paging. EAT in ns?

Numerical answer: \_\_\_\_\_\_\_\_

**Q10**NAT2 marksSegmentation

Segment table: segment 0 (base 1000, limit 700), segment 1 (3000, 200), segment 2 (5200, 1000). Physical address of (2, 750)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q11**NAT2 marksWorking set

Reference string 1 2 3 2 4 1 5 2 1 2 3 4 (positions 1–12), Δ = 4. Working-set size at t = 8?

Numerical answer: \_\_\_\_\_\_\_\_

**Q12**NAT2 marksInode

Inode with 10 direct, 1 single and 1 double indirect pointer; 1 KB blocks; 8-byte pointers. Maximum file size in KB?

Numerical answer: \_\_\_\_\_\_\_\_

### ✓Answer Vault

🔐 Open the Answer Vault

**Q1** Answer: (D)1 mark

It asks the kernel to do I/O.

- **(A) is wrong:** Pure library code.
- **(B) is wrong:** Pure library code.
- **(C) is wrong:** Pure library code.

Re-read: [Lesson 0.1.3](#l-0-1-3) — System calls: how programs ask the operating system for help

**Q2** Answer: (A)1 mark

A process must be running to request I/O or an event.

- **(B) is wrong:** The event happened.
- **(C) is wrong:** Pre-emption.
- **(D) is wrong:** An I/O request.

Re-read: [Lesson 1.1.1](#l-1-1-1) — Processes: memory layout, process control block and process states

**Q3** Answer: 4.252 marks

P1 0–5, P2 5–8, P4 8–10, P3 10–18: waits 0, 4, 8, 5.

Re-read: [Lesson 2.1.3](#l-2-1-3) — Priority scheduling, starvation and aging; highest response ratio next

**Q4** Answer: 2.33 to 2.342 marks

P2 (4 + 3)/3 ≈ 2.33; P3 (3 + 8)/8; P4 (2 + 2)/2.

Re-read: [Lesson 2.1.3](#l-2-1-3) — Priority scheduling, starvation and aging; highest response ratio next

**Q5** Answer: 0.93752 marks

1 − 0.5⁴.

Re-read: [Lesson 2.2.2](#l-2-2-2) — Multilevel queues, CPU and I/O bursts, CPU utilisation

**Q6** Answer: (B)1 mark

The wait condition needs flag\[j\] to be true.

- **(A) is wrong:** turn doesn't matter when flag\[j\] is false.
- **(C) is wrong:** That is strict alternation.
- **(D) is wrong:** No.

Re-read: [Lesson 3.1.2](#l-3-1-2) — Software solutions: turn and flag attempts, Peterson's algorithm

**Q7** Answer: 21 mark

5 − 12 + 9.

Re-read: [Lesson 3.2.1](#l-3-2-1) — Semaphores: wait, signal, counting and binary semaphores

**Q8** Answer: 42 marks

No request fits in (0, 0, 0), so nobody can finish.

Re-read: [Lesson 4.1.3](#l-4-1-3) — Detection, recovery, and the minimum-resources formula

**Q9** Answer: 1422 marks

0.9 × 130 + 0.1 × 250.

Re-read: [Lesson 5.2.2](#l-5-2-2) — TLBs, effective access time and multilevel page tables

**Q10** Answer: 59502 marks

750 \< 1000.

Re-read: [Lesson 5.2.3](#l-5-2-3) — Segmentation, and segmentation with paging

**Q11** Answer: 42 marks

References 5–8: 4 1 5 2.

Re-read: [Lesson 5.3.3](#l-5-3-3) — Frame allocation, thrashing, working sets and the clock algorithm

**Q12** Answer: 165222 marks

k = 128; 10 + 128 + 16384 blocks.

Re-read: [Lesson 6.1.2](#l-6-1-2) — Allocation methods: contiguous, linked (FAT), indexed (inodes); free space

Type next → [**7.2.3** Mixed practice set 3](#l-7-2-3)

## 🔁7.2.3 — Mixed practice set 3

Phase 7 › Integration & Final Test › Chapter 7.2 Mixed practice

Phase 7Ch 7.2 Mixed practice≈ 40 min

The last practice set. Time yourself: 1-mark questions under 90 seconds, 2-mark under 3 minutes.

⏱️

**12 questions · 18 marks · 40 minutes.** Negative marking on MCQ only: −1/3 mark for a wrong 1-mark MCQ, −2/3 for a wrong 2-mark MCQ. No negative marking for MSQ or NAT; MSQ has no partial credit.

**Q1**MCQ1 markTimer

Why does the OS set a hardware timer before giving the CPU to a user program?

1. (A) To measure the program's memory
2. (B) To protect files
3. (C) To speed up the program
4. (D) So that a program can't keep the CPU for ever

**Q2**MCQ1 markZombie

A child process has exited, but its parent has not yet called wait(). The child is:

1. (A) an orphan
2. (B) suspended
3. (C) a zombie
4. (D) running

**Q3**NAT2 marksFCFS

FCFS: P1 (arrival 2, burst 4), P2 (3, 2), P3 (10, 3), P4 (11, 1). Average turnaround time?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**NAT2 marksCPU + I/O

FCFS on the CPU, separate I/O devices. A (arrival 0): CPU 3, I/O 5, CPU 2. B (arrival 0): CPU 2, I/O 1, CPU 4. When does A finish?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**MCQ1 markSpinlocks

A spinlock is the better choice when:

1. (A) critical sections are very short and there are several CPUs
2. (B) critical sections are long and there is one CPU
3. (C) processes must sleep while waiting
4. (D) bounded waiting is required

**Q6**NAT2 marksRace with semaphore

`x = 0`. P1 and P2 each do `x = x + 3`; P3 does `x = x − 1`. Each brackets its read-modify-write with `wait(S)` … `signal(S)`, and S starts at 2. Largest possible final value of x?

Numerical answer: \_\_\_\_\_\_\_\_

**Q7**MCQ1 markPrevention

If the OS may take resources away from a waiting process, which deadlock condition is broken?

1. (A) Circular wait
2. (B) No pre-emption
3. (C) Hold and wait
4. (D) Mutual exclusion

**Q8**NAT2 marksTranslation

Pages are 4 KB. Logical address 13,000 is on page p, and page p is in frame 11. Physical address?

Numerical answer: \_\_\_\_\_\_\_\_

**Q9**NAT2 marksPage-fault EAT

ma = 150 ns, page-fault service 5 ms, fault rate 2 × 10⁻⁵. EAT in ns (nearest integer)?

Numerical answer: \_\_\_\_\_\_\_\_

**Q10**NAT2 marksFIFO

Reference string 1 2 3 2 4 1 5 2 1 2 3 4, 4 empty frames, FIFO. Number of page faults?

Numerical answer: \_\_\_\_\_\_\_\_

**Q11**NAT1 markLatency

A disk spins at 10,000 rpm. Average rotational latency in ms?

Numerical answer: \_\_\_\_\_\_\_\_

**Q12**NAT1 markInterrupts

A device interrupts 2000 times per second and each interrupt costs 50 µs. Percentage of CPU time used?

Numerical answer: \_\_\_\_\_\_\_\_

### ✓Answer Vault

🔐 Open the Answer Vault

**Q1** Answer: (D)1 mark

The timer interrupt returns control to the OS.

- **(A) is wrong:** Unrelated.
- **(B) is wrong:** That is permissions.
- **(C) is wrong:** No.

Re-read: [Lesson 0.1.2](#l-0-1-2) — What an operating system does: kernel, user mode and kernel mode, interrupts

**Q2** Answer: (C)1 mark

Its entry stays until the parent collects the exit status.

- **(A) is wrong:** An orphan's parent has exited.
- **(B) is wrong:** No.
- **(D) is wrong:** It has finished.

Re-read: [Lesson 1.1.2](#l-1-1-2) — Creating processes with fork(), exec() and wait(); context switches and schedulers

**Q3** Answer: 3.752 marks

Idle 0–2; P1 2–6, P2 6–8; idle 8–10; P3 10–13, P4 13–14: TAT 4, 5, 3, 3.

Re-read: [Lesson 2.1.1](#l-2-1-1) — Scheduling basics: the times we measure; first-come first-served

**Q4** Answer: 122 marks

A 0–3, B 3–5, B 6–10 (back from I/O at 6), A 10–12.

Re-read: [Lesson 2.2.2](#l-2-2-2) — Multilevel queues, CPU and I/O bursts, CPU utilisation

**Q5** Answer: (A)1 mark

Spinning briefly beats a context switch.

- **(B) is wrong:** Spinning wastes the holder's CPU time.
- **(C) is wrong:** That is a blocking semaphore.
- **(D) is wrong:** A plain TSL lock doesn't give it.

Re-read: [Lesson 3.1.3](#l-3-1-3) — Hardware help: test-and-set, compare-and-swap, spinlocks

**Q6** Answer: 62 marks

Lose the decrement: P3's −1 is overwritten.

Re-read: [Lesson 3.2.3](#l-3-2-3) — Monitors, and reasoning about concurrent code

**Q7** Answer: (B)1 mark

Resources can now be pre-empted.

- **(A) is wrong:** Not directly.
- **(C) is wrong:** Still holding while waiting.
- **(D) is wrong:** Still exclusive.

Re-read: [Lesson 4.1.2](#l-4-1-2) — Prevention and avoidance: safe states and the banker's algorithm

**Q8** Answer: 457682 marks

p = 3, offset 712; 11 × 4096 + 712.

Re-read: [Lesson 5.2.1](#l-5-2-1) — Paging: pages, frames, page tables and the address split

**Q9** Answer: 2502 marks

0.99998 × 150 + 2 × 10⁻⁵ × 5,000,000.

Re-read: [Lesson 5.3.1](#l-5-3-1) — Demand paging, page faults and effective access time

**Q10** Answer: 92 marks

1, 2, 3, 4 load; then 5, 1, 2, 3 and 4 each fault (the 2 right after 5 hits).

Re-read: [Lesson 5.3.2](#l-5-3-2) — Page replacement: FIFO, optimal and LRU; Belady's anomaly

**Q11** Answer: 31 mark

6 ms per rotation / 2.

Re-read: [Lesson 6.2.1](#l-6-2-1) — Disk structure and access time

**Q12** Answer: 101 mark

2000 × 50 µs = 0.1 s per second.

Re-read: [Lesson 6.2.3](#l-6-2-3) — I/O techniques: programmed I/O, interrupts, DMA, buffering and spooling

Type next → [**7.3.1** GATE pattern drill: recurring patterns and fastest methods](#l-7-3-1)

## 🔁7.3.1 — GATE pattern drill: recurring patterns and fastest methods

Phase 7 › Integration & Final Test › Chapter 7.3 GATE pattern drill

Phase 7Ch 7.3 GATE pattern drill≈ 45 min

GATE Operating Systems questions come back in a small number of shapes. For each shape: the cue in the question, the fastest method, and the lesson that teaches it.

| # | Pattern (cue) | Fastest method | Lesson |
| --- | --- | --- | --- |
| 1 | "how many times is X printed / processes created" (fork) | draw the process tree; n forks in a row → 2ⁿ processes, 2ⁿ − 1 children; trace && and \|\| short-circuits | [Lesson 1.1.2](#l-1-1-2) |
| 2 | average waiting / turnaround time | draw the Gantt chart; TAT = CT − AT, WT = TAT − BT | [Lesson 2.1.1](#l-2-1-1) |
| 3 | SRTF or pre-emptive priority | re-decide at **every arrival**; compare with the remaining time | [Lesson 2.1.2](#l-2-1-2) |
| 4 | round robin, context switches | keep the queue on paper; arrivals join before the pre-empted process | [Lesson 2.2.1](#l-2-2-1) |
| 5 | CPU idle with I/O bursts | only CPU bursts compete; I/O overlaps; idle at the start and end | [Lesson 2.2.2](#l-2-2-2) |
| 6 | "possible values of x" | load/compute/store; one-after-other values + "both read, last store wins" | [Lesson 3.1.1](#l-3-1-1) |
| 7 | "which requirement fails" | try both-in (ME), both-stuck (progress), one-starved (bounded waiting) | [Lesson 3.1.2](#l-3-1-2) |
| 8 | semaphore value / waiters | initial − waits + signals; negative = number waiting | [Lesson 3.2.1](#l-3-2-1) |
| 9 | semaphore code: deadlock or order | counting wait before mutex wait; opposite orders deadlock | [Lesson 3.2.2](#l-3-2-2) |
| 10 | banker's safe sequence / request | Need = Max − Alloc; Need ≤ Work → Work += Alloc | [Lesson 4.1.2](#l-4-1-2) |
| 11 | resources so deadlock is impossible | Σ(kᵢ − 1) + 1 | [Lesson 4.1.3](#l-4-1-3) |
| 12 | first / best / worst fit | place one request at a time, update the holes | [Lesson 5.1.1](#l-5-1-1) |
| 13 | page-table size, address split | offset = log₂(page); entries = 2^(page bits); × PTE size | [Lesson 5.2.1](#l-5-2-1) |
| 14 | TLB EAT, levels of paging | h(t + m) + (1 − h)(t + (k + 1)m); levels = ⌈page bits / log₂(page/PTE)⌉ | [Lesson 5.2.2](#l-5-2-2) |
| 15 | EAT with page faults | (1 − p)·ma + p·s; convert ms to ns | [Lesson 5.3.1](#l-5-3-1) |
| 16 | count page faults | write frames in columns; FIFO oldest, LRU least recent, OPT farthest | [Lesson 5.3.2](#l-5-3-2) |
| 17 | maximum file size (inode) | k = B/P; (direct + k + k² + k³) × B | [Lesson 6.1.2](#l-6-1-2) |
| 18 | disk access time | seek + half a rotation + transfer | [Lesson 6.2.1](#l-6-2-1) |
| 19 | total head movement | list requests on a number line; SCAN to the edge, LOOK to the last request | [Lesson 6.2.2](#l-6-2-2) |
| 20 | CPU share of I/O | events per second × cost per event | [Lesson 6.2.3](#l-6-2-3) |

⏱️

Time budget in the exam

1-mark questions: under 90 seconds. 2-mark questions: under 3 minutes. Scheduling and page-replacement traces are the slowest: draw the table once, neatly, and answer every sub-question from it.

⏱️

**8 questions · 16 marks · 45 minutes.** Negative marking on MCQ only: −1/3 mark for a wrong 1-mark MCQ, −2/3 for a wrong 2-mark MCQ. No negative marking for MSQ or NAT; MSQ has no partial credit.

**Q1**NAT2 marksPattern 1

How many processes exist in total (including the original) after `fork(); if (fork() == 0) fork(); printf("x");`?

Numerical answer: \_\_\_\_\_\_\_\_

**Q2**NAT2 marksPattern 2

All arrive at 0 with bursts 6, 2, 8, 3, 4 (SJF). Average waiting time?

Numerical answer: \_\_\_\_\_\_\_\_

**Q3**NAT2 marksPattern 6

`c = 10`. Three threads run `c = c + 2`, `c = c − 3` and `c = c + 1` concurrently (load/compute/store). How many different final values are possible?

Numerical answer: \_\_\_\_\_\_\_\_

**Q4**NAT2 marksPattern 11

5 processes share 11 units of one resource; each needs at most K. Largest K that guarantees no deadlock?

Numerical answer: \_\_\_\_\_\_\_\_

**Q5**NAT2 marksPattern 13

Logical addresses 40 bits, pages 16 KB, entries 8 bytes. Page-table size in MB?

Numerical answer: \_\_\_\_\_\_\_\_

**Q6**NAT2 marksPattern 16

Reference string 4 3 2 1 4 3 5 4 3 2 1 5, 3 empty frames, optimal replacement. Number of faults?

Numerical answer: \_\_\_\_\_\_\_\_

**Q7**NAT2 marksPattern 18

Average seek 8 ms, 7500 rpm, 200 sectors per track. Time to read 20 consecutive sectors in ms?

Numerical answer: \_\_\_\_\_\_\_\_

**Q8**NAT2 marksPattern 19

Head at 80; requests 45, 130, 10, 175, 90, 60, 150 (cylinders 0–199). C-LOOK moving towards higher cylinders, counting the jump. Total head movement?

Numerical answer: \_\_\_\_\_\_\_\_

### ✓Answer Vault

🔐 Open the Answer Vault

**Q1** Answer: 62 marks

2 after the first fork; each forks again, and only the children of that second fork fork once more: 2 + 2 + 2.

Re-read: [Lesson 1.1.2](#l-1-1-2) — Creating processes with fork(), exec() and wait(); context switches and schedulers

**Q2** Answer: 6.22 marks

Order 2, 3, 4, 6, 8: waits 0, 2, 5, 9, 15.

Re-read: [Lesson 2.1.2](#l-2-1-2) — Shortest job first and shortest remaining time first

**Q3** Answer: 72 marks

Every value from 7 to 13 can occur.

Re-read: [Lesson 3.1.1](#l-3-1-1) — Race conditions and the critical-section problem

**Q4** Answer: 32 marks

5(K − 1) + 1 ≤ 11.

Re-read: [Lesson 4.1.3](#l-4-1-3) — Detection, recovery, and the minimum-resources formula

**Q5** Answer: 5122 marks

2²⁶ entries × 8 B.

Re-read: [Lesson 5.2.1](#l-5-2-1) — Paging: pages, frames, page tables and the address split

**Q6** Answer: 72 marks

Optimal evicts the page needed farthest ahead.

Re-read: [Lesson 5.3.2](#l-5-3-2) — Page replacement: FIFO, optimal and LRU; Belady's anomaly

**Q7** Answer: 12.82 marks

8 + 4 + (20/200) × 8.

Re-read: [Lesson 6.2.1](#l-6-2-1) — Disk structure and access time

**Q8** Answer: 3102 marks

95 up to 175, 165 back to 10, 50 up to 60.

Re-read: [Lesson 6.2.2](#l-6-2-2) — Disk scheduling: FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK

Type next → [**7.4.1** Final end-to-end test (30 questions, 90 min)](#l-7-4-1)

## 🏆Final end-to-end test

Phase 7 › Integration & Final Test › Chapter 7.4 Final test

Phase 7Ch 7.4 Final test

Thirty questions in GATE format covering all phases (15 one-mark, 15 two-mark; 45 marks). Set a 90-minute timer, work on paper, and enter your answers in the boxes. For MSQ tick all correct options; for NAT enter a number. Then press **Submit answers**: the page scores you with GATE negative marking, shows topic-wise accuracy, lists the questions you got wrong and the lessons to re-read. The full key is at the very end of these notes.

Conventions: times in ms unless stated; KB = 2¹⁰ bytes; scheduling ties go to the earlier arrival; in round robin a process arriving when another is pre-empted joins the queue first; NAT decimals are accepted in a small range.

⏱️

**30 questions · 45 marks · 90 minutes.** Negative marking on MCQ only: −1/3 mark for a wrong 1-mark MCQ, −2/3 for a wrong 2-mark MCQ. No negative marking for MSQ or NAT; MSQ has no partial credit.

**Q1**NAT1 markAddress bits

How many address bits are needed for 4 GB of byte-addressable memory?

Your answer:

**Q2**MCQ1 markSystem calls

A user program switches from user mode to kernel mode to make a system call by:

1. (A) disabling interrupts
2. (B) changing the page table
3. (C) a subroutine call into the kernel's code
4. (D) a trap (software interrupt)

**Q3**MCQ1 markPCB

Which of these is NOT stored in a process control block?

1. (A) Process state
2. (B) List of open files
3. (C) The program's source code
4. (D) Program counter

**Q4**MCQ1 markThreads

With user-level threads mapped many-to-one, one thread makes a blocking system call. Then:

1. (A) the whole process blocks
2. (B) the kernel schedules another thread of the process
3. (C) only that thread blocks
4. (D) the call fails

**Q5**NAT1 markFCFS

Jobs with bursts 10, 5, 2 arrive at time 0 in that order (FCFS). Average waiting time (2 decimals)?

Your answer:

**Q6**MCQ1 markPre-emption

Which of these scheduling algorithms is non-pre-emptive?

1. (A) SRTF
2. (B) HRRN
3. (C) Pre-emptive priority
4. (D) Round robin

**Q7**MCQ1 markRequirements

Which requirement ensures that a process asking to enter its critical section will eventually get in, after a limited number of others?

1. (A) Progress
2. (B) Mutual exclusion
3. (C) Bounded waiting
4. (D) Atomicity

**Q8**NAT1 markSemaphore

A semaphore starts at 3. Then 5 wait and 2 signal operations complete. Final value?

Your answer:

**Q9**MCQ1 markDeadlock conditions

Which of these is NOT one of the four necessary conditions for deadlock?

1. (A) Mutual exclusion
2. (B) Circular wait
3. (C) Hold and wait
4. (D) Starvation

**Q10**NAT1 markMinimum resources

4 processes each need at most 2 units of a resource. Minimum units so that deadlock is impossible?

Your answer:

**Q11**MCQ1 markFragmentation

External fragmentation can be removed by:

1. (A) compaction
2. (B) increasing the page size
3. (C) using a TLB
4. (D) using fixed partitions

**Q12**NAT1 markOffset bits

How many offset bits are there with 8 KB pages?

Your answer:

**Q13**MCQ1 markBelady

Belady's anomaly can occur with:

1. (A) Optimal
2. (B) FIFO
3. (C) LRU
4. (D) Any stack algorithm

**Q14**MCQ1 markWorking set

The working set of a process at time t with window Δ is:

1. (A) the distinct pages referenced in its last Δ references
2. (B) all pages the process will ever use
3. (C) the last Δ pages loaded from disk
4. (D) the pages currently in its frames

**Q15**NAT1 markLatency

A disk spins at 12,000 rpm. Average rotational latency in ms?

Your answer:

**Q16**NAT2 marksfork()

How many times is "1" printed by `if (fork() || fork()) fork(); printf("1");`?

Your answer:

**Q17**NAT2 marksSRTF

A (arrival 0, burst 9), B (1, 4), C (2, 2), D (6, 3). SRTF: average turnaround time?

Your answer:

**Q18**NAT2 marksPre-emptive priority

P1 (arrival 0, burst 5, priority 3), P2 (2, 3, 1), P3 (3, 4, 2), P4 (5, 2, 4); smaller number = higher priority. Pre-emptive priority: average waiting time?

Your answer:

**Q19**NAT2 marksRound robin

P1 (arrival 0, burst 5), P2 (1, 4), P3 (3, 2), P4 (4, 3); RR with quantum 2. Number of context switches (changes between different processes; the first dispatch not counted)?

Your answer:

**Q20**NAT2 marksCPU + I/O

FCFS on the CPU, separate I/O devices. A (arrival 0): CPU 2, I/O 3, CPU 4. B (arrival 1): CPU 3, I/O 2, CPU 1. C (arrival 2): CPU 1, I/O 6, CPU 2. When does C finish?

Your answer:

**Q21**NAT2 marksRace with semaphore

`x = 0`. P1 and P2 each do `x = x + 3`; P3 does `x = x − 1`; each brackets its read-modify-write with `wait(S)` … `signal(S)`, and S starts at 2. How many different final values of x are possible?

Your answer:

**Q22**MSQ2 marksSemaphore code

Bounded buffer with mutex = 1, empty = N, full = 0. Which of these changes can cause a deadlock?

1. [ ] (A) Consumer does `wait(mutex)` before `wait(full)`
2. [ ] (B) Producer does `signal(full)` before `signal(mutex)`
3. [ ] (C) Consumer does `signal(empty)` before `signal(mutex)`
4. [ ] (D) Producer does `wait(mutex)` before `wait(empty)`

**Q23**MCQ2 marksBanker's

Available (1, 2, 1). Allocation: P0 (0,1,3), P1 (1,2,2), P2 (2,3,0), P3 (0,3,3). Max: P0 (3,4,5), P1 (1,3,2), P2 (4,5,3), P3 (1,7,3). Which is a safe sequence?

1. (A) P1, P0, P2, P3
2. (B) P3, P1, P2, P0
3. (C) P0, P1, P2, P3
4. (D) P1, P2, P0, P3

**Q24**NAT2 marksLevels

40-bit virtual addresses, 4 KB pages, 4-byte entries; every page table fits in one page. Number of levels?

Your answer:

**Q25**NAT2 marksEAT

Two-level paging, memory access 100 ns, TLB 20 ns, hit ratio 0.9. EAT in ns?

Your answer:

**Q26**NAT2 marksLRU

Reference string 4 3 2 1 4 3 5 4 3 2 1 5, 3 empty frames, LRU. Number of page faults?

Your answer:

**Q27**NAT2 marksMax fault rate

ma = 80 ns, page-fault service 4 ms. Largest fault rate (in units of 10⁻⁶, 2 decimals) so that EAT ≤ 120 ns?

Your answer:

**Q28**NAT2 marksInode

Inode with 10 direct, 1 single and 1 double indirect pointer; blocks 4 KB; pointers 8 bytes. Maximum file size in MB (2 decimals)?

Your answer:

**Q29**NAT2 marksC-SCAN

Head at 80; requests 45, 130, 10, 175, 90, 60, 150 (cylinders 0–199). C-SCAN towards higher cylinders, counting the return jump. Total head movement?

Your answer:

**Q30**NAT2 marksInterrupts

A disk delivers 1,024,000 bytes per second in 512-byte sectors, with one interrupt per sector costing 25 µs. Percentage of CPU time spent on these interrupts?

Your answer:

[Show the key](#final-key)

🎓 That is the whole course.

# 🔑Final Test — Answer Key

🛑

Stop here until you have finished the 90-minute final test.

🔑 Open the full answer key

**Q1** Answer: 321 mark

2³² bytes.

Re-read: [Lesson 0.1.1](#l-0-1-1) — Inside a computer: CPU, memory, disk, I/O; bits, bytes and powers of two

**Q2** Answer: (D)1 mark

The trap sets kernel mode and jumps to a fixed handler.

- **(A) is wrong:** Privileged.
- **(B) is wrong:** Privileged.
- **(C) is wrong:** An ordinary call can't change the mode.

Re-read: [Lesson 0.1.3](#l-0-1-3) — System calls: how programs ask the operating system for help

**Q3** Answer: (C)1 mark

The PCB stores state needed to run and manage the process.

- **(A) is wrong:** Stored.
- **(B) is wrong:** Stored.
- **(D) is wrong:** Stored.

Re-read: [Lesson 1.1.1](#l-1-1-1) — Processes: memory layout, process control block and process states

**Q4** Answer: (A)1 mark

The kernel sees one process.

- **(B) is wrong:** The kernel doesn't know the threads.
- **(C) is wrong:** True for one-to-one kernel threads.
- **(D) is wrong:** No.

Re-read: [Lesson 1.2.1](#l-1-2-1) — Threads: what they share, user-level vs kernel-level threads

**Q5** Answer: 8.33 to 8.341 mark

(0 + 10 + 15)/3.

Re-read: [Lesson 2.1.1](#l-2-1-1) — Scheduling basics: the times we measure; first-come first-served

**Q6** Answer: (B)1 mark

It runs the chosen job to completion.

- **(A) is wrong:** Shorter arrivals pre-empt.
- **(C) is wrong:** By definition.
- **(D) is wrong:** Time slices pre-empt.

Re-read: [Lesson 2.1.3](#l-2-1-3) — Priority scheduling, starvation and aging; highest response ratio next

**Q7** Answer: (C)1 mark

A bound on others' entries.

- **(A) is wrong:** About the decision not being postponed.
- **(B) is wrong:** About exclusivity.
- **(D) is wrong:** Not one of the three.

Re-read: [Lesson 3.1.1](#l-3-1-1) — Race conditions and the critical-section problem

**Q8** Answer: 01 mark

3 − 5 + 2.

Re-read: [Lesson 3.2.1](#l-3-2-1) — Semaphores: wait, signal, counting and binary semaphores

**Q9** Answer: (D)1 mark

Starvation is a different problem.

- **(A) is wrong:** A condition.
- **(B) is wrong:** A condition.
- **(C) is wrong:** A condition.

Re-read: [Lesson 4.1.1](#l-4-1-1) — Deadlock: the four conditions and resource-allocation graphs

**Q10** Answer: 51 mark

4 × 1 + 1.

Re-read: [Lesson 4.1.3](#l-4-1-3) — Detection, recovery, and the minimum-resources formula

**Q11** Answer: (A)1 mark

Moving processes together merges the holes.

- **(B) is wrong:** Paging has no external fragmentation anyway.
- **(C) is wrong:** Unrelated.
- **(D) is wrong:** Causes internal fragmentation instead.

Re-read: [Lesson 5.1.1](#l-5-1-1) — Addresses and contiguous allocation: fits and fragmentation

**Q12** Answer: 131 mark

2¹³ = 8 K.

Re-read: [Lesson 5.2.1](#l-5-2-1) — Paging: pages, frames, page tables and the address split

**Q13** Answer: (B)1 mark

More frames can mean more faults with FIFO.

- **(A) is wrong:** Stack algorithm.
- **(C) is wrong:** Stack algorithm.
- **(D) is wrong:** Stack algorithms are immune.

Re-read: [Lesson 5.3.2](#l-5-3-2) — Page replacement: FIFO, optimal and LRU; Belady's anomaly

**Q14** Answer: (A)1 mark

The window looks back Δ references.

- **(B) is wrong:** Too large.
- **(C) is wrong:** Loads are not references.
- **(D) is wrong:** Frames may hold other pages.

Re-read: [Lesson 5.3.3](#l-5-3-3) — Frame allocation, thrashing, working sets and the clock algorithm

**Q15** Answer: 2.51 mark

5 ms per rotation / 2.

Re-read: [Lesson 6.2.1](#l-6-2-1) — Disk structure and access time

**Q16** Answer: 52 marks

The parent's first fork returns non-zero, so it runs the inner fork. Its first child got 0, so it calls the second fork; it gets non-zero and runs the inner fork too. The child of that second fork got 0 both times and skips it. 5 processes, one print each.

Re-read: [Lesson 1.1.2](#l-1-1-2) — Creating processes with fork(), exec() and wait(); context switches and schedulers

**Q17** Answer: 7.52 marks

A 0–1, B 1–2, C 2–4, B 4–7, D 7–10, A 10–18: TAT 18, 6, 2, 4.

Re-read: [Lesson 2.1.2](#l-2-1-2) — Shortest job first and shortest remaining time first

**Q18** Answer: 42 marks

P1 0–2, P2 2–5, P3 5–9, P1 9–12, P4 12–14: waits 7, 0, 2, 7.

Re-read: [Lesson 2.1.3](#l-2-1-3) — Priority scheduling, starvation and aging; highest response ratio next

**Q19** Answer: 72 marks

P1 P2 P1 P3 P4 P2 P1 P4.

Re-read: [Lesson 2.2.1](#l-2-2-1) — Round robin and the time quantum

**Q20** Answer: 142 marks

A 0–2, B 2–5, C 5–6, A 6–10, B 10–11, idle 11–12, C 12–14.

Re-read: [Lesson 2.2.2](#l-2-2-2) — Multilevel queues, CPU and I/O bursts, CPU utilisation

**Q21** Answer: 52 marks

−1, 2, 3, 5 and 6.

Re-read: [Lesson 3.2.3](#l-3-2-3) — Monitors, and reasoning about concurrent code

**Q22** Answer: (A) (D)2 marks

Waiting on a counting semaphore while holding the mutex blocks the other side.

- **(B) is wrong:** Signals never block.
- **(C) is wrong:** Signals never block.

Re-read: [Lesson 3.2.2](#l-3-2-2) — Classic problems: bounded buffer, readers–writers, dining philosophers

**Q23** Answer: (D)2 marks

Needs: P0 (3,3,2), P1 (0,1,0), P2 (2,2,3), P3 (1,4,0). Work (1,2,1) → P1 → (2,4,3) → P2 → (4,7,3) → P0 → (4,8,6) → P3.

- **(A) is wrong:** After P1, Work (2,4,3) can't cover P0's 3.
- **(B) is wrong:** P3 needs 4 of the second type; only 2 are free.
- **(C) is wrong:** P0 needs 3 of the first type; only 1 is free.

Re-read: [Lesson 4.1.2](#l-4-1-2) — Prevention and avoidance: safe states and the banker's algorithm

**Q24** Answer: 32 marks

1024 entries per page → 10 bits per level; 28 page bits.

Re-read: [Lesson 5.2.2](#l-5-2-2) — TLBs, effective access time and multilevel page tables

**Q25** Answer: 1402 marks

0.9 × 120 + 0.1 × (20 + 300).

Re-read: [Lesson 5.2.2](#l-5-2-2) — TLBs, effective access time and multilevel page tables

**Q26** Answer: 102 marks

Every reference faults except the 4 and the 3 right after 5.

Re-read: [Lesson 5.3.2](#l-5-3-2) — Page replacement: FIFO, optimal and LRU; Belady's anomaly

**Q27** Answer: 9.99 to 10.012 marks

80 + p(4,000,000 − 80) ≤ 120.

Re-read: [Lesson 5.3.1](#l-5-3-1) — Demand paging, page faults and effective access time

**Q28** Answer: 1026.03 to 1026.052 marks

k = 512; (10 + 512 + 262144) × 4 KB.

Re-read: [Lesson 6.1.2](#l-6-1-2) — Allocation methods: contiguous, linked (FAT), indexed (inodes); free space

**Q29** Answer: 3782 marks

119 to 199, 199 back to 0, 60 up to 60.

Re-read: [Lesson 6.2.2](#l-6-2-2) — Disk scheduling: FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK

**Q30** Answer: 52 marks

2000 interrupts × 25 µs = 0.05 s per second.

Re-read: [Lesson 6.2.3](#l-6-2-3) — I/O techniques: programmed I/O, interrupts, DMA, buffering and spooling

GATE 2027 · Operating Systems — Complete Notes · 58 of 58 roadmap items ready.