Understanding Operating System Scheduling
Understanding Operating System Scheduling
Operating-
[Link]
Page 1
Page 2
Page 3
Page 4
Page 5
preemptive
Page 6
Page 7
Spooling (Simultaneous Peripheral Operations On-Line) in OS means storing data temporarily in a buffer (usually on disk) so that \
the CPU and I/O devices can work independently at their own speeds.
Example: In printer spooling, multiple print jobs are stored in a queue (spool) and the printer prints them one by one,
while the CPU continues working.
It improves CPU utilization, allows multiprocessing, and manages slow I/O devices efficiently.
Page 8
Page 9
Page 10
Page 11
Page 12
Page 13
The Degree of Multiprogramming in an operating system refers to the number of processes loaded into main memory (RAM) and actively
being managed by the CPU at a given time.
Detailed Explanation
1. Definition
○ It is the number of processes that are ready to execute (in main memory) at the same time.
○ It is not the total number of processes in the system (some might be on disk or suspended).
2. Purpose
○ To improve CPU utilization: When one process waits for I/O, another can use the CPU.
○ To reduce idle CPU time.
3. Example
○ If your OS has 4 processes in main memory at the same time, the degree of multiprogramming is 4.
4. Control
○ Controlled by a Long-Term Scheduler (also called Admission Scheduler).
○ If the degree is too high → risk of thrashing (excessive swapping between RAM and disk).
○ If too low → CPU underu liza on.
5. Formula (conceptual, not exact calculation)
Degree of Multiprogramming = Number of processes in memory
1. CPU Scheduling — Overview
• Definition:
CPU scheduling is the process of deciding which process in the ready queue gets the CPU next.
• Goal:
Maximize CPU utilization, throughput, and responsiveness while minimizing waiting time, turnaround time, and response time.
Page 14
2. Types of Scheduling
Scheduling can happen at different levels in an OS:
A. Long-Term Scheduling
• What it does:
Controls the degree of multiprogramming (how many processes are in main memory).
• Function:
Decides which processes are admitted into the system for processing.
• Characteristics:
○ Runs infrequently (seconds or minutes apart).
○ Balances I/O-bound and CPU-bound processes.
○ Implemented by Long-Term Scheduler (Admission Scheduler).
• Impact:
Too many processes → memory thrashing.
Too few processes → CPU idle.
B. Medium-Term Scheduling
• What it does:
Temporarily removes (suspends) some processes from memory and later resumes them.
• Function:
Optimizes the mix of I/O-bound and CPU-bound processes, controls multiprogramming level dynamically.
• Characteristics:
○ Improves performance by suspending low-priority or waiting processes.
○ Used in time-sharing systems to free up CPU for active processes.
○ Implemented by Medium-Term Scheduler.
C. Short-Term Scheduling
• What it does:
Decides which ready process will run next on the CPU.
• Function:
Selects from ready queue and dispatches to CPU.
• Characteristics:
○ Runs very frequently (milliseconds).
○ Has the most direct impact on system performance.
○ Implemented by Short-Term Scheduler (CPU Scheduler).
Page 15
WT = TAT - BT
Characteristics:
1. Non-preemptive – once a process starts execution, it cannot be stopped until it finishes.
2. Basis of Scheduling – Process arrival time.
3. Fairness – Each process gets CPU in the order of arrival.
4. Implementation – Managed with a simple FIFO queue.
Example:
Suppose 3 processes arrive as follows:
Process Arrival Time (AT) Burst Time (BT)
P1 0 5
P2 1 3
P3 2 8
Step 1 – Arrange in order of arrival
Already ordered: P1 → P2 → P3
Step 2 – Calculate Completion Time (CT)
• P1: CT = 0 + 5 = 5
• P2: CT = 5 + 3 = 8
• P3: CT = 8 + 8 = 16
Step 3 – Calculate TAT & WT
Process AT BT CT TAT = CT-AT WT = TAT-BT
P1 0 5 5 5 0
P2 1 3 8 7 4
P3 2 8 16 14 6
Averages:
• Avg TAT = (5+7+14) / 3 = 8.67
• Avg WT = (0+4+6) / 3 = 3.33
Page 16
• Avg WT = (0+4+6) / 3 = 3.33
Gantt Chart:
| P1 | P2 | P3 |
0 5 8 16
Advantages:
• Simple to implement.
• Fair: processes are served in the order they arrive.
• No starvation.
Disadvantages:
• Convoy Effect: Short processes may wait for long processes to finish.
• Poor average waiting time if burst times vary a lot.
Use Cases:
• Best for batch systems where execution time is predictable and processes are not interactive.
Characteristics:
1. Based on burst time (BT), not arrival order.
2. Optimal algorithm – gives minimum average waiting time if all processes are known in advance.
3. Implementation needs knowledge of burst times (can be predicted using exponential averaging in real systems).
Page 17
P3 2 2
P4 3 1
Execution:
• At 0 → P1 starts (BT=8).
• At 1 → P2 arrives (BT=4 < remaining 7) → preempt P1, run P2.
• At 2 → P3 arrives (BT=2 < remaining 3) → preempt P2, run P3.
• At 3 → P4 arrives (BT=1 < remaining 1 of P3? No, equal → con nue P3).
• P3 finishes, then P4, then P2, then P1.
Order: P1 → P2 → P3 → P4 → P2 → P1
Result: Gives smaller average waiting time than non-preemptive.
When BT for two process=- same follow fcfs
Advantages:
• Minimum average waiting time (optimal).
• Good for batch jobs where execution times are predictable.
Disadvantages:
• Needs knowledge of burst time (not realistic always).
• Response time is poor.
• May cause starvation – longer processes may never execute if short ones keep arriving.
• Preemptive SJF has higher overhead due to frequent context switching.
Use Cases:
• Suitable for batch processing systems where job lengths are known.
Characteristics:
1. Scheduling is based on priority (not arrival or burst time).
2. Priority may be internally defined (based on resource needs, memory usage, etc.) or externally defined (business importance, user
requirement).
3. Processes with the same priority are scheduled using FCFS.
Important Terms:
• Priority number: Lower number = higher priority (or vice-versa, depends on system convention).
• AT, BT, CT, TAT, WT are calculated as usual.
Page 18
Averages:
• Avg TAT = (5+7+11+20)/4 = 10.75
• Avg WT = (0+4+5+12)/4 = 5.25
Gantt Chart:
| P1 | P2 | P4 | P3 |
0 5 8 14 22
Advantages:
• Flexible (can give priority to important processes).
• Useful in real-time systems.
Disadvantages:
• Starvation (indefinite blocking): Low-priority processes may never execute if high-priority processes keep coming.
• Can be solved with Aging → gradually increase the priority of wai ng processes.
• New Priority=Old Priority+(Waiting Time×α)
Use Cases:
• Real-time OS (where urgent tasks must execute first).
• Systems where different types of jobs (interactive vs background) exist.
Characteristics:
1. Preemptive version of FCFS.
2. Time Quantum (q): Decides efficiency.
○ If q is too large → works like FCFS.
○ If q is too small → more context switches, high overhead.
3. Fair → every process gets an equal share of CPU in cyclic order.
4. Best suited for time-sharing systems.
5. Best avg response time
6. Ready queue is circular queue
7. Context switching is used.
Example:
Process AT BT
P1 0 5
P2 1 4
P3 2 2
Time Quantum (q) = 2
Step-by-Step Execution:
• At 0 → P1 runs for 2 units → remaining BT = 3
• At 2 → P2 arrives → run P2 for 2 units → remaining BT = 2
• At 4 → P3 arrives → run P3 for 2 units → finishes
• Back to P1 (remaining 3) → run 2 units → remaining 1
• Next P2 (remaining 2) → run 2 units → finishes
• Finally P1 (remaining 1) → run 1 unit → finishes
Execution Order (Gantt Chart):
| P1 | P2 | P3 | P1 | P2 | P1 |
0 2 4 6 8 10 11
CT, TAT, WT Table:
Process AT BT CT TAT=CT-AT WT=TAT-BT
P1 0 5 11 11 6
P2 1 4 10 9 5
P3 2 2 6 4 2
Averages:
Page 19
Averages:
• Avg TAT = (11+9+4)/3 = 8.0
• Avg WT = (6+5+2)/3 = 4.33
After a certain time quantum RR=FCFS
Advantages:
• Fair → no starva on.
• Good for time-sharing & interactive systems.
• Simple to implement.
Disadvantages:
• Performance depends heavily on time quantum (q).
• High context switching overhead if q is too small. As time quantum is inversely proportional tp context switching
• Larger average waiting time compared to SJF. Means starvation
Use Cases:
• Interactive systems (user processes, servers, multitasking).
• Time-sharing OS like UNIX.
🔹 Multilevel Queue (MLQ) Scheduling
Definition:
• Ready queue is divided into multiple separate queues based on process type/priority.
• Each queue has its own scheduling algorithm.
• A fixed priority is given to each queue → processes in higher priority queues are executed first.
Structure Example:
• Queue 1 (Highest priority): System processes → Scheduled by RR (q=10 ms).
• Queue 2: Interactive processes → Scheduled by RR (q=20 ms).
• Queue 3: Batch processes → Scheduled by FCFS.
Diagram (Text Form):
[ Queue 1: System ] → RR
[ Queue 2: Interac ve ] → RR
[ Queue 3: Batch ] → FCFS
Characteristics:
1. Rigid – once a process is assigned to a queue, it stays there permanently.
2. Each queue can have its own algorithm.
3. Queues scheduled based on fixed priority.
Advantages:
• Simple to implement.
• Useful for systems with clear process categories (foreground vs background).
Disadvantages:
• Rigid – process can’t move between queues.
• Starvation possible → low-priority queues may never execute.
Page 20
Characteristics:
• Dynamic – processes can move up or down queues.
• Prevents starvation by eventually pushing all processes to lower FCFS queue.
• More complex to implement than MLQ.
Advantages:
• More flexible than MLQ.
• Adapts to process behavior.
• Good for general-purpose time-sharing systems.
Disadvantages:
• Complex to tune (time quantum, number of queues, promotion/demotion rules).
• Higher overhead due to frequent queue adjustments.
🔹 Threads in OS
Definition:
• A thread is the smallest unit of CPU execution.
• Single sequence stream within a process
• A process can have multiple threads that share the same address space, code, and resources, but run independently.
• Sometimes called lightweight process (LWP).
🔹 Process vs Thread
Feature Process Thread
System call req No System call
Definition Independent program in execution Smallest execution unit inside a process
Memory Has its own memory (PCB, address space) Shares memory of process (code, data, files) as treated as single task for os
Overhead Heavyweight (more overhead) Lightweight (less overhead)
Communication Inter-process Communication (IPC) needed Easier (shared memory within process)
Switching Slower (context switch between processes) Faster (context switch between threads)
🔹 Types of Threads
1. User Threads (UT):
○ Managed at user level (not kernel).
○ Created by application
○ No use of kernel
○ Has own program counter, register set and data files
○ Faster to create & manage.
○ Thread switching is fast.
○ OS not aware → if one thread blocks or it causes page fault , the whole process blocks.
2. Kernel Threads (KT):
○ Managed by OS kernel.
○ Slower (more overhead).
○ Efficient
Thread control Block- overhead
Page 21
○ Thread control Block- overhead
○ It does not block entire process.
○ OS schedules threads individually → be er CPU u liza on.
3. Hybrid (User + Kernel):
○ Many user threads mapped to fewer kernel threads (M: N model).
○ Tries to combine advantages of both.
🔹 Thread Models
1. Many-to-One:
○ Many user threads mapped to one kernel thread.
○ Simple but one blocked thread blocks all.
2. One-to-One:
○ Each user thread maps to a kernel thread.
○ True concurrency, but high overhead.
3. Many-to-Many:
○ Many user threads mapped to many kernel threads.
○ Flexible, balanced model.
○ Blocking system call does not block the entire process.
🔹 Benefits of Threads
1. Responsiveness: One thread blocked doesn’t block entire process.
2. Resource Sharing: Threads share memory & resources.
3. Economy: Cheaper to create/manage than processes.
4. Scalability: Efficient use of multiprocessor systems.
Process Synchronization
• Definition:
Process synchronization is a mechanism to ensure that when multiple processes execute concurrently, their execution is coordinated so
that shared resources are accessed in a safe and consistent manner.
○ Prevents race conditions (when outcome depends on the order of execution).
○ Ensures data consistency in a multi-process system.
Methods of IPC
1. Shared Memory
○ A region of memory is shared between cooperating processes.
○ Fast, as processes directly read/write to memory.
○ Needs synchronization (semaphores/monitors).
○ Example: Producer-Consumer problem using a buffer.
○ Kernel is not involved.
2. Message Passing
○ Processes communicate by sending/receiving messages through the OS.
○ Slower than shared memory (more overhead).
○ Easier for distributed systems.
○ Example: Client-server communication.
○ Kernel is involved.
○ Message Passing Operations:
send(message) → send info to another process.
receive(message) → receive info from another process.
Page 23
🔹 Race Condition
Definition:
• A race condition occurs when multiple processes/threads access shared data concurrently, and the final outcome depends on the order
of execution.
Example:
Two threads updating a shared variable x = 5:
• Thread 1: x = x + 1
• Thread 2: x = x * 2
• If Thread 1 runs first → result = 12
• If Thread 2 runs first → result = 10
👉 Output is inconsistent → this is a race condition.
Cause: Lack of synchronization while accessing shared resources.
🔹 Critical Section
Definition:
• The part of the program where a process accesses shared resources (variables, files, databases, etc.) is called the Critical Section.
• Only one process should be allowed in the critical section at a time.
🔹 Semaphores
Definition:
• A semaphore is a synchronization primitive (a special integer variable) used to control access to shared resources by multiple
processes/threads.
• Proposed by Edsger Dijkstra (1965).
• Used to handle mutual exclusion.
🔹 Types of Semaphores
1. Binary Semaphore (Mutex Lock):
○ Value = 0 or 1.
○ Works like a simple lock → either resource is free (1) One means entry is allowed or taken (0 means not allowed)
○ Used for mutual exclusion.
2. Counting Semaphore:
○ Value ≥ 0 (integer). From - infintiy to + infinity
○ Used to manage access to multiple instances of a resource.
○ Example: Printer pool with 3 printers → ini al semaphore = 3.
🔹 Operations on Semaphore
Two atomic operations (can’t be interrupted):
1. Wait (P operation / down): used in entry section
Page 24
1. Wait (P operation / down): used in entry section
wait(S):
while S <= 0:
// busy wait (or block)
S=S-1
○ If S > 0 → decrement and proceed.
○ If S = 0 → process waits un l resource is free. No process are nin suspend list
○ If S<0 --> this no of process are on suspend list
2. Signal (V operation / up/ post/ release): exit section
signal(S):
S=S+1
○ Increments the semaphore value.
○ Wakes up a waiting process if any.
Deadlock
A deadlock is a situation in which a set of processes are blocked because each process is holding a resource and waiting for another resource
held by some other process.
• In short: Circular waiting → No one proceeds → System stuck.
Page 25
1. Deadlock Prevention (Prevent at least one Coffman condition):
○ Mutual Exclusion: Not always possible (printers, etc.).
○ Hold & Wait: Require processes to request all resources at once.
○ No Preemption: Allow resource preemption.
○ Circular Wait: Impose an ordering of resources, and processes can only request resources in increasing order.
2. Deadlock Avoidance (Safe state check):
○ Uses Banker’s Algorithm.
○ Before allocating resources, check if system will remain in a safe state.
○ Safe state → At least one sequence of process execu on exists where all processes complete.
3. Deadlock Detection & Recovery:
○ Allow deadlock to occur, then detect using a Wait-for Graph (nodes = processes, edges = wait).
○ Recovery: Kill processes or preempt resources.
4. Ignore Deadlock:
○ Many OS (like UNIX, Windows) just ignore deadlock because handling is costly and rare.
Resource Allocation Graph (RAG / RG)
A Resource Allocation Graph is a directed graph used to represent the state of a system in terms of processes and resources. It is mainly used
for deadlock detection and prevention.
Components:
1. Processes (P1, P2, …, Pn) → represented as circles.
2. Resources (R1, R2, …, Rm) → represented as rectangles.
○ Each rectangle has small dots inside, representing instances of that resource.
3. Edges:
○ Request edge (Pi → Rj): Process Pi is requesting resource Rj.
○ Assignment edge (Rj → Pi): Resource Rj is assigned to process Pi.
Deadlock in RAG:
• If the graph has no cycle → No deadlock.
• If the graph has a cycle →
○ Single instance per resource: Cycle = Deadlock.
○ Multiple instances per resource: Cycle may or may not be a deadlock.
Example:
1. Process P1 requests R1
(P1 → R1 edge drawn).
2. R1 allocated to P2
(R1 → P2 edge drawn).
3. If P2 is waiting for R2, and R2 is allocated to P1 → A cycle is formed → Deadlock occurs.
For mininum no of resource allocation request not to have a deadlock follow the below method,
Page 26
Memory Management in OS
Memory management is the process of allocating and deallocating memory to processes efficiently so that CPU utilization is maximized and
response time is minimized.
Two Major Types:
3. Compaction
○ Process of shifting processes to remove external fragmentation.
○ Undesirable as we need to stop running process also
○ Allocation and deallocation process is complex so bitmap and linked list is used.
3.
4. Advantages of Paging
○ No external fragmentation (only internal fragmentation).
○ Efficient use of memory.
○ Easy process swapping.
○ Supports virtual memory.
5. Disadvantages of Paging
○ Overhead of maintaining page tables.
○ Internal fragmentation (last page may not fully use frame).
○ Slower memory access (extra lookup in page table).
○ Large processes → large page tables.
6. Types of Paging
○ Simple Paging: Single-level page table.
○ Multilevel Paging: Page table itself paged foreasy storage in RAM (reduces memory overhead).
○ Inverted Page Table: One entry per frame, not per page (saves space). That is it creates global page table for all the process. So not
of entries = no of frames.
○ Demand Paging: Load pages into memory only when needed (used in virtual memory).
7. Page Replacement Algorithms (for demand paging)
○ FIFO (First In First Out)
○ LRU (Least Recently Used)
○ Optimal Page Replacement
○ Clock Algorithm
8. Performance Factors
○ Hit Ratio = fraction of memory accesses found in TLB/cache.
○ Effective Access Time (EAT) =
EAT = (Hit Ratio × TLB Access Time) + (Miss Ratio × (TLB Time + Memory Time))
○ Solves external fragmentation, but may cause internal fragmentation.
2. Segmentation
Segmentation is a memory management technique in which a process is divided into different segments based on the logical divisions of a
program such as code, data, stack, heap, etc.
Unlike paging (which divides memory into fixed-size blocks), segmentation divides it into variable-sized blocks depending on the program’s
needs.
CPU has no idea of segmentation it is also done by MMU like paging
Key Features
Page 28
Key Features
1. Logical Division – Program is divided into meaningful units (e.g., functions, arrays, objects).
2. Variable Size – Each segment can have a different size.
3. Segment Table – Maintains:
○ Segment Number (ID)
○ Base Address (starting address of segment in physical memory)
○ Limit (Length) (size of segment)
4. Addressing in Segmentation – A logical address has two parts:
○ Segment Number
○ Offset (Displacement within segment)
Then,
Physical Address = Base Address (from Segment Table) + Offset
5. Protection – Each segment can have protection bits (read/write/execute). Also called d bits which telll how to read… and until where.
Advantages
• Reflects programmer’s view of memory (logical grouping).
• Supports dynamic growth (stack, heap).
• Easier to apply protection and sharing (e.g., two processes sharing a code segment).
Disadvantages
• Leads to external fragmentation (since segments are variable size).
• Harder memory allocation compared to paging.
👉 Example:
If a process has 3 segments:
• Segment 0 (Code) – 2 KB
• Segment 1 (Data) – 1.5 KB
• Segment 2 (Stack) – 1 KB
Segment table will map each segment’s base + limit, and logical address (segment no, offset) is translated accordingly.
3. Paged Segmentation (Hybrid)
○ Combines both paging + segmentation.
○ Each segment is divided into pages.
Thrashing in OS
Definition
Thrashing is a situation in virtual memory management where the system spends more time swapping pages between main memory and
disk (paging) than executing the actual process instructions.
Symptoms of Thrashing
• CPU utilization decreases (because CPU is waiting for I/O due to page faults).
• High page fault rate.
• System becomes slow and unresponsive.
Example Flow
Page 29
Example Flow
1. Multiprogramming ↑
2. More processes → fewer frames per process
3. Page fault rate ↑↑
4. CPU utilization ↓
5. OS may try to increase multiprogramming (wrong decision)
6. Leads to vicious cycle → Thrashing
Virtual Memory in OS
Definition
Virtual memory is a memory management technique that provides an illusion of a large main memory to the user by combining hardware
(MMU), software (OS), and secondary storage (disk).
It allows programs to execute even if they are larger than the physical RAM available.
Key Concepts
1. Address Space
○ Logical (Virtual) Address Space: Generated by the CPU (seen by processes).
○ Physical Address Space: Actual location in main memory (RAM).
○ Virtual memory maps logical addresses to physical addresses using page tables.
2. Demand Paging
○ Only required pages of a program are loaded into RAM.
○ Rest are kept on the disk until needed.
○ Reduces memory usage.
3. Page Fault
○ Occurs when a program accesses a page not present in RAM.
○ OS fetches the page from secondary storage → loads it into RAM.
4. Thrashing
○ If too many page faults occur, the CPU spends more time swapping pages than executing instructions → severe performance drop.
5. Page Replacement Policies
○ Decide which page to remove from RAM when space is needed:
FIFO (First-In-First-Out)
LRU (Least Recently Used)
Optimal Page Replacement
Important Terminologies
1. Memory Access Time (m)
○ Time required to access data from main memory.
○ Example: 100 ns.
2. TLB Access Time (t)
○ Time required to check the Translation Lookaside Buffer.
○ Example: 10 ns.
3. Hit Ratio (h)
○ Probability that the page number is found in the TLB.
○ Range: 0 ≤ h ≤ 1.
Example: h = 0.9 (i.e., 90% times address found in TLB).
Page 30
○ Example: h = 0.9 (i.e., 90% times address found in TLB).
4. Miss Ratio (1 – h)
○ Probability that the page number is not found in TLB.
5. Page Fault Rate (p)
○ Probability that the required page is not in memory.
○ Example: p = 0.001.
6. Page Fault Service Time (S)
○ Extra time needed to handle a page fault (fetch page from disk).
○ Disk access is very slow (in ms).
EAT Calculation
Case 1: Without Page Faults (only TLB and Memory)
EAT = (h × (t + m)) + ((1 – h) × (t + 2m))
Explanation:
• If TLB Hit → Need TLB lookup + 1 memory access → (t + m).
• If TLB Miss → Need TLB lookup + 2 memory accesses (page table + data) → (t + 2m).
Example
Suppose:
• m = 100 ns
• t = 10 ns
• h = 0.9
• p = 0 (no page fault)
EAT = (0.9 × (10 + 100)) + (0.1 × (10 + 200))
EAT = (0.9 × 110) + (0.1 × 210)
EAT = 99 + 21
EAT = 120 ns
Disadvantages
• More page faults can cause slower performance.
• Thrashing in case of improper allocation.
• Requires extra hardware support (MMU).
Page 31
• Excessive page faults → Thrashing (CPU spends more time handling faults than executing processes).
Definition
• Roll-In Roll-Out is a swapping technique used in multiprogramming OS.
• Here, processes are moved between main memory (RAM) and backing store (disk/secondary storage) to make space for other processes.
Roll-In
• When a process is swapped out of main memory into secondary storage.
• Usually done when memory is full, or a higher-priority process needs to be loaded.
• Example: Process P1 is paused and copied from RAM → Disk.
Roll-Out
• When a process that was previously swapped out is brought back into main memory from secondary storage so it can continue execution.
• Example: P1 is needed again → Disk → RAM.
Use Case
• Used when there is memory shortage and multiple processes are competing for CPU.
• Allows the system to temporarily suspend some processes and later resume them.
Key Points
• It increases degree of multiprogramming but also increases overhead (because swapping takes time).
• Usually combined with scheduling (like priority scheduling).
• High-priority processes may roll out lower-priority ones.
Page Replacement
When a process tries to access a page that is not present in main memory (RAM), a page fault occurs.
If the memory (frames) is full, the operating system needs to replace one of the existing pages in memory with the new page from disk.
The decision of which page to replace is made by a Page Replacement Algorithm.
Key Terms:
1. Page Fault – When the required page is not in RAM.
2. Frame – A fixed-size block of physical memory.
3. Page – A fixed-size block of logical (virtual) memory.
4. Page Replacement Algorithm – Strategy to select which page should be replaced.
2.
Performance Evaluation:
• Page Fault Rate = (Number of page faults) / (Total memory accesses).
• Lower page fault rate ⇒ Better performance.
Page 33
○ Unlike main memory (volatile), disks are non-volatile and can permanently store data.
○ OS manages disk space and scheduling for efficient I/O operations.
1. Disk Structure
A magnetic disk has several components:
○ Platter: Circular disk made of magnetic material. Data is stored on the platter surface.
○ Track: Concentric circles on a platter surface.
○ Sector: Subdivision of a track (smallest unit of data storage, typically 512B or 4KB).
○ Cylinder: Set of tracks at the same position across all platters.
○ Head: Reads/writes data on a platter surface.
○ Arm: Holds the head and moves it across tracks.
○ Spindle: Rotates the platters at constant speed (e.g., 5400 rpm, 7200 rpm).
1. Disk Addressing
○ Data is accessed using CHS (Cylinder, Head, Sector) or more commonly Logical Block Addressing (LBA).
○ LBA treats the disk as a linear array of blocks (simplifies addressing).
○ SSTF (Shortest Seek Time First) – selects request closest to current head position.
○ SCAN (Elevator Algorithm) – head moves in one direction, services requests, then reverses.
Page 34
○ C-SCAN (Circular SCAN) – only services in one direction, provides uniform wait time.
○ LOOK and C-LOOK – optimized versions of SCAN and C-SCAN (stop at last request instead of end of disk).
1. Disk Management by OS
○ Disk formatting: Prepares disk into sectors and file system.
○ Boot block: Contains bootstrap loader.
○ Free space management: Keeps track of unused blocks.
○ File allocation methods:
Contiguous
Linked
Indexed
4. File Operations
• Create – make a new file.
• Open – load file into memory for use.
• Read/Write – access or modify contents.
• Seek – reposition file pointer.
• Delete – remove file.
• Close – release memory/resources after use.
5. Directory Structure
Directories = special files that hold metadata + list of files.
Types:
1. Single-level directory – one directory for all files (confusing in large systems).
2. Two-level directory – separate directory for each user.
3. Tree-structured directory – hierarchy like Windows Explorer.
4. Acyclic-graph directory – allows shared files via links.
5. General graph directory – includes cycles (requires garbage collection).
Page 36
• Passwords – per-file or per-user.
• Encryption – protect file contents.
Here are detailed notes on Process Synchronization in Operating Systems (exam-oriented but clear enough for understanding):
1. Introduction
• In a multiprogramming environment, multiple processes may execute concurrently and share system resources (CPU, memory, files, etc.).
• Process synchronization is the coordination of processes so that they can execute in a safe and consistent manner when sharing resources.
2. Race Condition
• Occurs when multiple processes access and manipulate shared data concurrently, and the final output depends on the execution order.
• Example: Two processes updating a shared variable x simultaneously → inconsistent result.
To avoid race condition → we need synchroniza on.
3. Critical Section Problem
• Critical Section (CS): A part of the program where shared resources are accessed.
• To ensure correctness, only one process should execute in CS at a time.
Structure of a process with CS:
do {
Entry Section // Request to enter CS
Critical Section // Access shared resource
Exit Section // Release CS
Remainder Section// Other code
} while (true);
4. Requirements for Critical Section Solution
A valid solution must satisfy:
1. Mutual Exclusion → Only one process at a me in CS.
2. Progress → If no process is in CS, decision of who enters next should not be delayed.
3. Bounded Waiting → Each process must get a chance within a bounded number of turns (no starva on).
5. Software Solutions
• Peterson’s Algorithm (for 2 processes).
• Dekker’s Algorithm.
• Both use variables (turn & flag) to ensure mutual exclusion.
6. Hardware Solutions
Page 37
6. Hardware Solutions
• Test-and-Set (TSL instruction) → atomic instruc on used for locks.
• Swap instruction → used in busy-wait locks.
Disadvantage: Leads to busy waiting (CPU wasted).
7. Synchronization Tools
1. Semaphores (Dijkstra):
○ Integer variable used for signaling.
○ Types: Counting Semaphore & Binary Semaphore (mutex).
○ Operations:
wait(S): while S <= 0; S--;
signal(S): S++;
○ Used for mutual exclusion and process coordination.
2. Mutex Locks:
○ Special kind of binary semaphore.
○ Provides mutual exclusion using acquire() and release().
○ Example: Used in thread libraries.
3. Monitors:
○ High-level synchronization construct.
○ Allows only one process inside monitor at a time.
○ Uses condition variables (wait, signal) for coordination.
9. Deadlock vs Synchronization
• Deadlock: Processes wait forever (circular waiting).
• Synchronization: Controlled access, prevents race conditions.>
Page 38
SJF chooses tasks based on the shortest burst time rather than arrival order, resulting in the optimal minimum average waiting time if burst times for all processes are known . However, it requires knowledge of burst times, which is often unrealistic, and may cause starvation for longer processes if short ones keep arriving. This optimization also incurs higher overhead in its preemptive form due to frequent context switching .
In preemptive scheduling algorithms like Shortest Remaining Time First (SRTF), a process with a shorter burst time preempts the currently running process. This results in frequent context switching as new processes arrive with burst times shorter than the remaining time of the running process. The arrival times significantly influence the number of context switches, as each new process arrival could lead to a switch, particularly if the new process has a high priority or short burst time .
The Translation Lookaside Buffer (TLB) is a cache that stores recent translations of virtual-to-physical addresses, helping avoid page table lookups in main memory for every address translation. The TLB's hit ratio significantly impacts Effective Access Time (EAT); high hit ratios reduce average memory access time since lookups are resolved within the TLB, bypassing slower page table searches. Conversely, a low hit ratio increases EAT due to frequent misses requiring additional memory accesses .
Priority scheduling can lead to starvation because low-priority processes may never execute if high-priority processes continue to arrive. This issue is common in real-time systems where certain tasks are constantly prioritized. To mitigate starvation, a technique called 'Aging' is used, which gradually increases the priority of waiting processes over time, thus ensuring they eventually get executed .
The time quantum in Round Robin scheduling is critical as it determines the slice of CPU time each process receives before being preempted. If the quantum is too large, the system behaves like FCFS, potentially hurting responsiveness. If too small, it causes frequent context switches, increasing overhead and reducing efficiency. The optimal quantum balances these factors, providing good response time while maintaining reasonable overhead .
Demand paging improves memory utilization by loading pages into RAM only as needed, minimizing memory usage compared to traditional methods where all pages might be loaded unnecessarily. This approach reduces the footprint of data in RAM, allowing for better management of available memory and enabling larger applications to run on systems with limited physical memory .
Thrashing occurs when a system spends more time swapping pages in and out of memory than executing processes, often due to a high page fault rate from insufficient physical memory or improper process scheduling. Strategies to control thrashing include adjusting the size of memory frames, reducing the degree of multiprogramming by suspending some processes, increasing the physical memory size, or optimizing page replacement algorithms .
Paging is a memory management technique that avoids external fragmentation by allowing non-contiguous storage of a process's logical address space. However, it can cause internal fragmentation, as the last page may not completely fill its frame. While paging efficiently uses memory and supports virtual memory by reducing external fragmentation, it requires management of page tables and may incur overhead due to internal fragmentation .
In preemptive SJF, scheduling decisions are made whenever a new process arrives. If multiple processes arrive simultaneously, the one with the shortest burst time takes priority for execution. For example, if at time 0 two processes arrive with burst times 8 and 2, the process with burst time 2 will be preemptively selected over the other, regardless of when they started or their arrival order .
FCFS is simple to implement and fair, as it processes tasks in the order they arrive, ensuring no starvation . However, it suffers from the convoy effect, where short processes wait for long ones to finish, leading to poor average waiting time if burst times vary significantly .