OS Suggestion
OS Suggestion
Transition Reason
Short-Term Medium-Term
Feature Long-Term Scheduler
Scheduler Scheduler
Admit new
Action Choose next process Swap processes
processes
Example
Selecting jobs Context switching Reducing memory load
Scenario
Conclusion:
Schedulers are vital for the smooth and efficient operation of a multitasking operating
system. While the long-term scheduler manages the job queue and system load, the
short-term scheduler decides which process uses the CPU, and the medium-term
scheduler ensures optimal memory usage through swapping. Together, they maintain
performance, responsiveness, and fairness in the system.
Scheduling Algorithms in Operating System
1. What is a Scheduling Algorithm?
• A scheduling algorithm is a strategy used by the CPU scheduler to decide the
order in which processes in the ready queue are executed.
• The main goals include:
o Minimizing waiting time
o Maximizing CPU utilization
o Fairness among processes
o Reducing turnaround and response time
Types of CPU Scheduling Algorithms`
1. First Come First Serve (FCFS)
• Working: Processes are executed in the order they arrive.
• Type: Non-preemptive.
• Advantage: Simple and easy to implement.
• Disadvantage: Causes convoy effect (slow process delays faster ones).
Example:
Arrival: P1(0s), P2(2s), P3(4s)
Burst: P1(5s), P2(3s), P3(1s)
Execution order: P1 → P2 → P3
2. Shortest Job Next (SJN) / Shortest Job First (SJF)
• Working: Process with the shortest burst time is executed first.
• Type: Can be preemptive (Shortest Remaining Time First - SRTF) or non-
preemptive.
• Advantage: Minimum average waiting time.
• Disadvantage: Can cause starvation for long processes.
Example:
P1(6), P2(2), P3(4) → Execution: P2 → P3 → P1
3. Round Robin (RR)
• Working: Each process is given a fixed time slot (quantum). After that, the CPU
switches to the next process.
• Type: Preemptive.
• Advantage: Fair to all processes; good for time-sharing systems.
• Disadvantage: Performance depends on quantum size.
Example:
Time quantum = 2
P1(4), P2(3), P3(5) → Order: P1→P2→P3→P1→P2→P3→...
4. Priority Scheduling
• Working: Each process is assigned a priority; the highest priority process runs
first.
• Type: Can be preemptive or non-preemptive.
• Advantage: Important tasks get preference.
• Disadvantage: Starvation for low-priority tasks.
Example:
P1(priority 3), P2(priority 1), P3(priority 2) → Order: P2 → P3 → P1
Aging technique is used to prevent starvation by gradually increasing the priority
of waiting processes.
5. Multilevel Queue Scheduling
• Working: Processes are divided into multiple queues based on priority/type
(foreground, background).
• Each queue may have its own scheduling algorithm.
• No process moves between queues.
• Advantage: Organizes process types efficiently.
• Disadvantage: Rigid structure, no movement between queues.
6. Multilevel Feedback Queue Scheduling
• Improvement over Multilevel Queue.
• Allows process movement between queues based on execution history and
behavior.
• If a process uses more CPU time, it moves to a lower-priority queue.
• Prevents starvation by adjusting priority dynamically.
Comparison Table of Algorithms
Conclusion
Scheduling algorithms are the heart of process management in an operating system.
The choice of algorithm affects the efficiency, responsiveness, and fairness of the
system. Real-world systems often use a hybrid of these algorithms to suit different
types of workloads, balancing throughput and user satisfaction.
Deadlock in Operating System
1. Definition of Deadlock
• A deadlock is a situation where a group of processes are blocked indefinitely,
each waiting for a resource that is held by another process in the group.
• No process can proceed, and all are stuck in a circular wait.
2. Example of Deadlock
• Process P1 holds a printer and requests a scanner.
• Process P2 holds the scanner and requests the printer.
• Neither releases its resource, both keep waiting forever.
3. Necessary Conditions for Deadlock (Coffman's Conditions)
For deadlock to occur, all four of these must be true at the same time:
1. Mutual Exclusion: A resource is assigned to only one process at a time.
2. Hold and Wait: A process is holding one resource and waiting for others.
3. No Preemption: A resource cannot be taken away; it must be released
voluntarily.
4. Circular Wait: A set of processes are waiting in a circular chain.
4. Resource Allocation Graph (RAG)
• Used to represent processes and resources as a graph.
• If a cycle is present in the graph, deadlock may occur.
• If each resource has only one instance, a cycle means deadlock.
5. Deadlock Handling Techniques
A. Deadlock Prevention
• Design the system to deny one of the four conditions.
• Example: Do not allow hold-and-wait by requiring all resources to be requested
at once.
B. Deadlock Avoidance
• Check in advance whether a request leads to an unsafe state.
• Uses Banker’s Algorithm to determine a safe sequence.
C. Deadlock Detection and Recovery
• Let deadlocks occur, then detect and fix them.
• Use a Wait-For Graph to detect cycles.
• Recovery by:
o Killing processes
o Taking back resources
D. Ignore the Problem
• Use the Ostrich Algorithm.
• Assume deadlocks are rare, do nothing.
• Used in Windows, Linux and other general OS.
6. Deadlock vs Starvation
7. Conclusion
Deadlock is a major issue in multiprogramming systems where resources are limited.
It can lead to permanent process blocking. Understanding its conditions and handling
methods such as prevention, avoidance, detection, and recovery is critical to system
reliability.
Banker’s Algorithm in Operating System
1. What is Banker’s Algorithm?
• Banker’s Algorithm is a deadlock avoidance algorithm.
• It checks whether allocating a resource to a process leads to a safe state or not.
• Named Banker’s Algorithm because it works like a bank that loans resources
only if it is sure it can meet the future demands of all its customers (processes).
• Designed by Edsger Dijkstra.
2. Key Concepts in Banker’s Algorithm
To use Banker’s Algorithm, the system maintains the following data structures:
1. Available:
o Shows the number of available instances of each resource type.
o Example: If Available = [3, 2, 2], it means 3 instances of A, 2 of B, 2 of C
are available.
2. Max:
o The maximum demand of each process.
o Tells how much each process may need in total.
3. Allocation:
o The number of resources currently allocated to each process.
4. Need:
o The remaining resources each process still needs.
o Calculated as: Need = Max - Allocation
3. Safe State
• A system is in a safe state if there exists a safe sequence of process execution.
• In a safe sequence, each process can finish with the current available resources
and the resources released by previous processes.
4. Working of Banker’s Algorithm
Step-by-step process:
1. When a process requests resources:
o Check if Request ≤ Need
o Check if Request ≤ Available
2. If both conditions are true:
o Temporarily allocate the resources.
o Check if the system is still in a safe state using the Safety Algorithm.
3. If safe:
o Grant the request permanently.
4. If not safe:
o Roll back the allocation and make the process wait.
5. Example of Banker’s Algorithm
Let’s assume:
• Resource types: A, B, C
• Total resources: A=10, B=5, C=7
P0 753010 743
P1 322200 122
P2 902302 600
P3 222211 011
P4 433002 431
• Available = [3 3 2]
To check if the system is in a safe state, we try to find a safe sequence where each
process can finish.
Safe sequence found: P1 → P3 → P4 → P0 → P2
Since all processes can complete, the system is in a safe state.
6. Advantages of Banker’s Algorithm
• Helps the system to avoid deadlock completely.
• Ensures that resource allocation decisions do not push the system into unsafe
state.
7. Disadvantages of Banker’s Algorithm
• Needs to know the maximum resource needs of each process in advance.
• Complex and expensive to implement in large systems.
• Cannot be used in dynamic environments where resource needs change
frequently.
8. Banker’s Algorithm vs Deadlock Prevention
Conclusion
Banker’s Algorithm is a powerful tool for deadlock avoidance in systems with fixed
maximum resource demands. Though it is not widely used in modern operating
systems due to its limitations, it forms the theoretical basis for understanding safe
resource allocation and system safety.
Semaphore in Operating System
1. What is a Semaphore?
• A semaphore is a synchronization tool used to control access to shared
resources in a concurrent system such as a multiprogramming OS.
• It is a non-negative integer variable used to solve problems like race
conditions, mutual exclusion, and deadlocks.
2. Why Semaphore is Needed?
• When multiple processes access shared resources (e.g., printers, variables,
files), they must not interfere with each other.
• Semaphores help synchronize access to ensure only one process accesses a
resource at a time, preventing data inconsistency.
3. Types of Semaphores
There are two main types of semaphores:
A. Binary Semaphore (Mutex)
• Takes only two values: 0 and 1
• Used for mutual exclusion
• Acts like a lock
• If value is 1 → resource is free
• If value is 0 → resource is locked
B. Counting Semaphore
• Value can range from 0 to any positive integer
• Used to control access to a resource pool with multiple instances
• Example: 3 printers → semaphore initialized to 3
4. Operations on Semaphore
Semaphore operations are atomic (indivisible) and are used to manage the
semaphore value.
There are two standard operations:
A. Wait (also called P or down)
• Decreases the value of the semaphore by 1
• If value becomes less than 0, the process waits (is blocked)
B. Signal (also called V or up)
• Increases the value of the semaphore by 1
• If there are waiting processes, one of them is woken up
5. Working Example
Let’s say there is a printer and two processes P1 and P2 want to use it:
• Initialize Semaphore S = 1 (printer is free)
• P1 calls Wait(S) → S becomes 0 → P1 starts printing
• P2 calls Wait(S) → S is 0 → P2 waits
• P1 finishes and calls Signal(S) → S becomes 1 → P2 resumes
6. Use Cases of Semaphores
• Mutual exclusion: Only one process can enter a critical section at a time.
• Producer-Consumer Problem: Semaphores help producers and consumers
access a shared buffer without conflict.
• Reader-Writer Problem: Controls access where multiple readers or one writer
can access a resource.
• Dining Philosophers Problem: Classic synchronization problem solved using
semaphores.
7. Advantages of Semaphores
• Simple to implement and use
• Can be used to solve complex process synchronization problems
• Prevents race conditions and data inconsistency
8. Disadvantages of Semaphores
• Busy waiting: In some implementations, blocked processes waste CPU cycles
• Deadlocks: If not used properly, semaphores can lead to deadlocks
• Difficult to debug: Errors due to improper use of semaphores are hard to find
9. Semaphore vs Mutex
Conclusion
Semaphores are essential tools in operating systems for handling process
synchronization and resource management. By using wait and signal operations
properly, semaphores help prevent issues like race conditions, deadlocks, and data
corruption when multiple processes try to access shared resources concurrently.
Memory Allocation in Operating System
1. What is Memory Allocation?
• Memory allocation is the process by which the operating system assigns
memory blocks to programs and processes when they need it.
• It ensures that the available memory (RAM) is used efficiently and shared
properly among all running processes.
2. Types of Memory Allocation
Memory allocation is generally of two types:
A. Static Memory Allocation
• Memory is allocated at compile time.
• Size and location of memory are fixed.
• Cannot be changed during execution.
• Used in embedded systems, firmware, etc.
B. Dynamic Memory Allocation
• Memory is allocated at runtime.
• Used in general-purpose OS where programs may change their memory usage.
• Involves system calls like malloc(), calloc(), free() in C.
3. Main Memory Allocation Methods in OS
These methods are used by the OS to manage physical memory allocation:
A. Contiguous Memory Allocation
• Each process is allocated a single continuous block of memory.
• Simple and fast, but may lead to fragmentation.
Types of Contiguous Allocation:
1. Single Partition Allocation
o Only one user process at a time in memory.
o Used in old systems.
2. Multiple Partition Allocation
o Memory is divided into multiple partitions.
o Processes are assigned partitions as needed.
B. Non-Contiguous Memory Allocation
• A process’s memory is divided into small parts stored in non-adjacent blocks.
• Solves fragmentation problems of contiguous allocation.
Two Main Techniques:
1. Paging
o Memory is divided into fixed-size pages.
o Logical memory and physical memory are mapped using a page table.
o Avoids external fragmentation.
2. Segmentation
o Memory is divided into variable-sized segments like code, data, stack.
o Each segment has a segment number and offset.
o More flexible than paging.
4. Fragmentation in Memory Allocation
• Fragmentation occurs when memory is wasted due to inefficient allocation.
A. Internal Fragmentation
• Wasted space inside allocated memory block.
• Happens when fixed-size memory is larger than needed.
B. External Fragmentation
• Wasted space between allocated blocks.
• Happens in contiguous allocation when enough total free space exists but not
in a single block.
5. Memory Allocation Techniques
When allocating memory dynamically, OS uses the following strategies:
1. First Fit
o Allocate the first free block that is large enough.
o Fast but can leave small holes.
2. Best Fit
o Allocates the smallest block that fits the process.
o Reduces waste but may cause more fragmentation.
3. Worst Fit
o Allocates the largest block available.
o Leaves large leftover space but not always efficient.
6. Swapping
• A technique where processes are moved between RAM and disk to free up
memory.
• Allows OS to handle more processes than RAM can hold.
• May cause high disk I/O (slowdowns) if overused.
7. Virtual Memory
• Logical concept where a process believes it has more memory than physically
available.
• Uses disk space as an extension of RAM.
• Implemented through paging and segmentation.
8. Importance of Memory Allocation
• Ensures efficient use of RAM.
• Supports multiprogramming by allowing many processes to run.
• Reduces the chances of system crashes due to memory conflicts.
Conclusion
Memory allocation is a critical function of the operating system that determines how
RAM is distributed among active processes. Whether done statically or dynamically,
contiguously or with paging and segmentation, proper memory management ensures
system stability, speed, and multitasking capabilities.
Memory Fragmentation in Operating Systems
Memory fragmentation refers to a condition where the available memory is broken
into small, scattered pieces, making it difficult for the operating system to allocate
large contiguous blocks of memory to processes. Even if the total amount of free
memory is enough to satisfy a process’s request, fragmentation may prevent the
allocation due to the lack of a single large block.
There are two main types of fragmentation: internal fragmentation and external
fragmentation.
Internal fragmentation happens when memory is allocated in fixed-size blocks, but
the process does not use the entire space allocated. For example, if a process only
needs 10 KB but is given a 12 KB block (because memory can only be allocated in
fixed-size chunks), the extra 2 KB is wasted — this wasted space inside the allocated
region is called internal fragmentation.
On the other hand, external fragmentation occurs when free memory is available but
scattered across different locations. This means that although the sum of free space is
sufficient to satisfy a large memory request, it cannot be allocated because there’s no
large enough contiguous block. For example, suppose we have free blocks of 30 KB,
20 KB, and 50 KB scattered in memory, but a process needs 70 KB. Even though the
total free space is 100 KB, the request will fail because there’s no single block of 70
KB.
To solve fragmentation, operating systems use different techniques. One of the
traditional solutions to external fragmentation is compaction, where all the used
memory blocks are moved together, and the free memory blocks are combined into
one large block. However, compaction is time-consuming and not always practical
during multitasking. A more effective solution is using paging and segmentation,
where memory is allocated in non-contiguous chunks, allowing processes to be
spread across the memory without needing one big block.
Virtual memory systems also help reduce the problems caused by fragmentation by
abstracting physical memory and allowing processes to use memory in a logical, linear
manner, even if it’s scattered physically.
Virtual Memory in Operating Systems
Virtual memory is a concept used in modern operating systems that allows a process
to think it has access to a large, continuous block of memory, even though the actual
physical memory (RAM) may be limited and fragmented. In simple terms, virtual
memory is an illusion that the system creates to make programming and multitasking
easier.
The idea behind virtual memory is to extend the available memory by using both
RAM and disk space. When the system runs out of RAM, it temporarily transfers some
data from RAM to a space on the hard disk called the swap space or page file. This
way, the OS can handle processes that need more memory than is physically available
in RAM.
To implement virtual memory, the OS divides memory into pages (small fixed-size
blocks). When a process runs, only the required pages are loaded into RAM. If a page
that the process needs is not in RAM, a page fault occurs, and the OS fetches that
page from the disk and loads it into RAM. This mechanism is called paging.
Virtual memory also enables process isolation, which means that each process gets its
own virtual address space and cannot directly access the memory of other processes.
This improves both security and stability because one program crashing will not affect
the memory of another.
Moreover, virtual memory allows multiprogramming, where multiple processes can
run simultaneously, even if their combined memory requirement exceeds the physical
RAM. It also simplifies memory management because the OS can allocate memory to
processes dynamically and flexibly.
Although virtual memory improves flexibility and multitasking, it comes with a cost —
using the disk as memory is much slower than RAM. Too much swapping between
RAM and disk can cause a condition called thrashing, where the system spends more
time swapping pages than executing processes, leading to performance issues.
Page Replacement Algorithms in Operating Systems
Page replacement algorithms are used in a system that implements virtual memory
with paging. Since physical RAM is limited, not all pages of all processes can be kept in
memory at the same time. So, when a process needs a page that is not in RAM (called
a page fault), the operating system has to decide which page to remove from memory
to make space for the required one. This decision-making process is handled by page
replacement algorithms.
These algorithms aim to reduce the number of page faults, which occur when the
system tries to access a page that is not currently in memory.
Let’s go over the most commonly used page replacement algorithms:
1. First-In-First-Out (FIFO)
This is the simplest algorithm. It replaces the oldest page in memory — the one that
was loaded first.
For example, if three pages can be kept in memory and pages A, B, and C are loaded
in that order, then if a new page D is needed, A (the oldest) will be removed.
Advantage: Simple to implement
Disadvantage: Doesn’t consider how frequently or recently a page is used, which can
lead to high page faults in some cases.
2. Least Recently Used (LRU)
This algorithm removes the page that was least recently used. It is based on the
assumption that pages used recently will likely be used again soon, and pages not
used for a long time are less likely to be needed.
It requires keeping track of the order in which pages are accessed.
Advantage: More efficient than FIFO in most cases
Disadvantage: Harder to implement because it needs to keep track of access history
(requires time-stamps or stacks)
3. Optimal Page Replacement
This is a theoretical algorithm that always removes the page that will not be used for
the longest time in the future.
Since it looks ahead into the future, it gives the lowest possible page fault rate, but it
cannot be implemented in real-time systems. It’s used mainly for comparison
purposes.
Advantage: Best performance
Disadvantage: Not practical because the future cannot be predicted
4. Least Frequently Used (LFU)
This algorithm removes the page that is used least often. It keeps a counter for how
many times each page is accessed.
Advantage: Useful when some pages are accessed regularly but not recently
Disadvantage: May keep pages that were used frequently in the past but are no
longer needed
5. Most Recently Used (MRU)
This is the opposite of LRU. It removes the most recently used page. It is used in some
cases where it's believed that recent access may not happen again soon — such as in
some database or file system workloads.
6. Clock Algorithm (Second Chance)
This is a more efficient version of FIFO. It arranges pages in a circular list with a
reference bit for each page. When a page is accessed, its reference bit is set to 1.
When replacement is needed, the algorithm goes in a circle to find a page with a
reference bit 0 and replaces it. If the bit is 1, it gives a second chance by turning it to 0
and moving on.
Advantage: Balances performance and simplicity
Disadvantage: Still an approximation of LRU, not always optimal
Why are Page Replacement Algorithms Important?
They help the OS manage limited RAM efficiently, reduce page faults, and ensure that
programs run faster. The better the algorithm, the fewer the interruptions to program
execution.
Example Scenario:
Imagine you have only 3 page frames and the process wants to access this page
sequence:
ABCABDADBC
Now depending on the algorithm used (FIFO, LRU, etc.), the number of page faults
will differ.
Disk Scheduling Algorithms in Operating Systems
In a computer system, the disk drive is a crucial component used to store and retrieve
data. But since the disk arm (the mechanical arm that reads or writes data on the
disk) takes time to move between tracks, it becomes important to schedule the disk
access requests efficiently to reduce seek time and improve overall performance. The
operating system uses disk scheduling algorithms to decide the order in which the
pending disk I/O requests should be served.
Let’s understand some of the most commonly used disk scheduling algorithms:
First-Come, First-Served (FCFS)
This is the simplest disk scheduling algorithm. It processes disk requests in the order
they arrive. If three processes request access to the disk at positions 40, 20, and 10,
and the head is currently at 50, the requests will be served in that exact order — no
optimization is applied.
While this method is easy to implement, it is often inefficient because it may result in
high total head movement and increased seek time, especially when requests are far
apart from each other.
Shortest Seek Time First (SSTF)
This algorithm selects the request that is closest to the current position of the disk
head. For example, if the head is at 50 and there are requests at 20, 35, and 70, the
head will move to the nearest track (35 in this case) first.
SSTF generally performs better than FCFS in terms of average seek time. However, it
has a drawback — starvation. Some requests might have to wait for a very long time if
newer, closer requests keep arriving.
SCAN (Elevator Algorithm)
The SCAN algorithm moves the disk head in one direction (say from outer to inner
tracks), servicing all requests in that direction until it reaches the end. Then it reverses
direction and services the remaining requests.
This movement is similar to an elevator that picks up people on its way up, then turns
around and does the same on its way down. SCAN provides better performance than
FCFS and SSTF, especially under heavy load.
LOOK
LOOK is an optimized version of SCAN. Instead of going all the way to the end of the
disk, the head only goes as far as the last request in that direction, then it reverses.
So, it doesn’t move unnecessarily to the physical end of the disk if there’s no request
waiting there.
LOOK reduces unnecessary seek time and is more efficient than SCAN in many
scenarios.
C-SCAN (Circular SCAN)
In this method, the head moves in one direction only (like SCAN), but when it reaches
the end, it jumps back to the beginning without servicing any requests on the return
trip. Then it starts servicing requests again in the same direction.
C-SCAN provides more uniform wait times and avoids favoring the middle tracks,
which can happen in regular SCAN.
C-LOOK
This is a variant of C-SCAN. Instead of moving to the end of the disk, the head moves
only as far as the last request in the current direction, and then it jumps back to the
lowest-numbered pending request to continue servicing.
C-LOOK minimizes head movement further and is one of the most efficient algorithms
in terms of performance.
Conclusion
Disk scheduling algorithms help reduce seek time, increase the speed of disk access,
and make the system more efficient. While FCFS is simple, it's usually inefficient. SSTF
is better but may cause starvation. Algorithms like SCAN, LOOK, C-SCAN, and C-LOOK
offer a good balance between fairness and performance, especially in systems with
heavy disk I/O loads.