OPERATING SYSTEM AND ITS TYPES
An operating system (OS) is software that manages computer hardware
and software resources. It acts as a bridge between users and the
computer, ensuring smooth operation. Different types of OS serve
different needs; some handle one task at a time, while others manage
multiple users or real-time processes.
1. Batch Operating System
A Batch Operating System is designed to handle large groups of similar jobs
efficiently. It does not interact with the computer directly but instead processes jobs
that are grouped by an operator. These jobs are queued and executed one after the
other, without user interaction during the process.
Processes groups of similar jobs automatically in batches without
user interaction.
Advantages of Batch Operating System
• Minimal Idle Time: The system minimizes idle time by processing jobs in a continuous
sequence without human intervention.
• Handling Repetitive Tasks: Ideal for managing large, repetitive tasks, such as payroll and
billing, with minimal effort.
• Improved Throughput: Batch systems can handle high volumes of jobs at once, improving
overall system throughput.
Disadvantages of Batch Operating System
• Inefficient CPU Utilization: When a job is waiting for input/output (I/O), the CPU remains idle,
leading to poor utilization of resources.
• Increased Response Time: The time between job submission and output can be high as all
jobs are processed sequentially.
• Lack of Real-Time Feedback: Users cannot interact with the system in real-time, making it
less suitable for interactive tasks.
Examples:
• Payroll Systems
• Bank Statements
2. Multi-Programming Operating System
In a Multi-Programming Operating System, multiple programs run in memory at the
same time. The CPU switches between programs, utilizing its resources more
effectively and improving overall system performance.
Runs multiple programs in memory at the same time to maximize CPU
usage.
Advantages
• Better CPU Utilization: CPU stays busy by switching to another job during I/O wait.
• Improved Throughput: Multiple jobs run concurrently, increasing work done per unit time.
• Efficient Resource Use: CPU, memory, and I/O devices are shared effectively among
processes.
Disadvantages
• Complex Design: Requires advanced memory management and CPU scheduling.
• Security Issues: More programs in memory increase chances of unauthorized access.
• High Memory Requirement: Needs larger RAM to run multiple programs together.
• Banking systems
• Railway servers
• Billing machines
3. Multi-tasking/Time-sharing Operating
systems
Multitasking OS is a type of multiprogramming system where each process runs in a
round-robin manner. Every task gets a fixed time slice called a quantum. After the
quantum ends, the OS switches to the next task, allowing multiple tasks—whether
from one user or many—to run smoothly on a single system.
Allows multiple tasks to run by giving each a small time slice for
smooth, shared system use.
Advantages
• Equal CPU Access: Each task gets a fair share of CPU time.
• Reduced Software Duplication: Many users can run the same software without needing
separate copies.
• Low CPU Idle Time: Efficient scheduling keeps the CPU busy.
Disadvantages
• Lower Reliability: System failures affect all users.
• Security Concerns: Multiple users increase risks to data integrity and privacy.
• Communication Issues: Data sharing between users can cause conflicts.
• IBM VM/CMS
• TSO (Time Sharing Option
• Windows Terminal Services
4. Multi-Processing Operating System
A Multi-Processing Operating System is a type of Operating System in which more
than one CPU is used for the execution of resources. It betters the throughput of the
System.
Uses two or more CPUs simultaneously to increase speed and
reliability.
Advantages
• Faster Processing: Multiple CPUs work simultaneously, increasing overall system speed.
• High Reliability: If one processor fails, others can continue working (fault tolerance).
• Supports Heavy Tasks: Ideal for computation-intensive applications like scientific or
industrial tasks.
Disadvantages
• High Cost: Multiple processors and complex hardware increase system cost.
• Complex Design: Requires advanced OS support for communication and task distribution.
• Not Always Efficient: Poor task distribution can lead to idle processors and wasted resources.
• UNIX
• Linux (Ubuntu, Red Hat, Debian)
• macOS
5. Distributed Operating System
Distributed operating systems connects multiple independent computers through a
shared communication network. Each system has its own CPU and memory but works
together as a single unit. The main benefit is remote access, allowing users to use files
and software stored on other connected systems.
Connects multiple independent computers to function as a single
coordinated system.
Advantages
• Independent Systems: Failure of one machine does not affect others.
• Easily Scalable: New systems can be added to the network easily.
• Lower Processing Delays: Tasks are handled faster across multiple machines.
Disadvantages
• Network Dependency: If the main network fails, communication stops.
• Lack of Standardization: No well-defined language or model for building such systems.
• High Cost & Complexity: Hardware is expensive, and the software is complex and not widely
understood.
Issues With Distributed Operating System
• Networking causes delays in the transfer of data between nodes of a distributed system.
Such delays may lead to an inconsistent view of data located in different nodes and make it
difficult to know the chronological order in which events occurred in the system.
• Control functions like scheduling, resource allocation and deadlock detection have to be
performed in several nodes to achieve computation speedup and provide reliable operation
when computers or networking components fail.
• Messages exchanged by processes present in different nodes may travel over public
networks and pass through computer systems that are not controlled by the distributed
operating system. An intruder may exploit this feature to tamper with messages or create
fake messages to fool the authentication procedure and masquerade as a user of the system.
Examples:
• LOCUS
• MICROS
• Amoeba
6. Network Operating System
A Network Operating System (NOS) runs on a server and manages data, users,
security, applications, and other network functions. It allows shared access to files,
printers, and resources within a small private network. Users can see the configuration
and connections of other users, which is why these systems are considered tightly
coupled systems.
Manages and supports users, data, and security across connected
computers within a network.
Advantages
• Centralized and Stable Servers: Provide reliable management of resources.
• Easy Upgrades: New hardware and technologies can be added without difficulty.
• Remote Access: Users can access the server from different locations and devices.
Disadvantages
• High Server Cost: Setting up and maintaining servers is expensive.
• Dependency on Server: Most operations rely on a central server.
• Regular Maintenance Needed: Frequent updates and technical support are required.
Examples:
• Microsoft Windows Server 2003
• UNIX, Linux
• Mac OS X
7. Real-Time Operating System
These types of OSs serve real-time systems. The time interval required to process and
respond to inputs is very small. This time interval is called response time. Real-time
systems are used when there are time requirements that are very strict like missile
systems, air traffic control systems, robots, etc.
Types of Real-Time Operating Systems
• Hard Real-Time Operating System: Used where strict timing is essential and any delay is
unacceptable, such as airbags or automatic parachutes. These systems avoid virtual memory
to ensure immediate response.
• Soft Real-Time Operating System: Used where timing is important but minor delays are
acceptable. These systems aim to give quick and predictable responses but do not require
perfect accuracy. They are commonly used in multimedia applications, gaming, video
streaming, and other interactive tasks.
8. Mobile Operating Systems
Mobile operating systems are designed specifically for mobile devices such as
smartphones and tablets. Examples of such operating systems are Android and iOS.
These operating systems manage the hardware and software resources of the device,
providing a platform for running applications and ensuring a seamless user experience.
Runs on smartphones and tablets, managing hardware, apps, and touch-
based interfaces.
Advantages
• User-Friendly Interfaces: Mobile operating systems are designed to be intuitive and easy to
use, making them accessible to a wide range of users.
• Extensive App Ecosystems: The availability of a vast number of applications allows users to
customize their devices to meet their specific needs.
• Connectivity Options: Mobile operating systems support multiple connectivity options,
enabling users to stay connected wherever they go.
Disadvantages
• Battery Life Constraints: Despite advancements in power management, battery life remains
a challenge for mobile devices, especially with heavy usage.
• Security Risks: Mobile devices are susceptible to various security threats, such as malware
and phishing attacks, which can compromise user data.
• Fragmentation: In the case of Android, the wide range of devices and customizations can
lead to fragmentation, making it difficult for developers to ensure compatibility across all
devices.
• Android
• iOS
• Blackberry
Key Differences
Feature Multiprogramming Multitasking
Objective CPU utilization User responsiveness
CPU switching When a process waits Time-sliced
Interaction Low High
OS Type Batch OS Time-sharing OS
Network Operating System (NOS)
Meaning: An OS that allows computers to communicate and share resources over a
network.
System View: Each computer has its own OS and works independently.
Resource Management: Resources are managed locally by each machine.
Transparency: Users are aware of different machines in the network.
Failure Handling: Failure of one system does not affect others.
Examples: Windows Server, UNIX, Linux (networked systems).
Use Case: File sharing, printer sharing, email servers.
Distributed Operating System (DOS)
Meaning: An OS that manages a group of computers and makes them appear as a
single system.
System View: All machines work together under one OS.
Resource Management: Resources are managed globally.
Transparency: Users are not aware of multiple systems.
Failure Handling: Failure of one node may affect the whole system.
Examples: Amoeba, Plan 9.
Use Case: High-performance computing, distributed databases.
History of Operating System
An operating system is a type of software that acts as an interface between the user
and the hardware. It is responsible for handling various critical functions of the
computer and utilizing resources very efficiently so the operating system is also
known as a resource manager. The operating system also acts like a government
because just as the government has authority over everything, similarly the operating
system has authority over all resources. Various tasks that are handled by OS are file
management, task management, garbage management, memory management, process
management, disk management, I/O management, peripherals management, etc.
Generations of Operating Systems
• 1940s-1950s: Early Beginnings
o Computers operated without operating systems (OS).
o Programs were manually loaded and run, one at a time.
o The first operating system was introduced in 1956. It was a batch
processing system GM-NAA I/O (1956) that automated job handling.
• 1960s: Multiprogramming and Timesharing
o Introduction of multiprogramming to utilize CPU efficiently.
o Timesharing systems, like CTSS (1961) and Multics (1969), allowed
multiple users to interact with a single system.
• 1970s: Unix and Personal Computers
o Unix (1971) revolutionized OS design with simplicity, portability, and
multitasking.
o Personal computers emerged, leading to simpler OSs like CP/M (1974)
and PC-DOS (1981).
• 1980s: GUI and Networking
o Graphical User Interfaces (GUIs) gained popularity with systems like
Apple Macintosh (1984) and Microsoft Windows (1985).
o Networking features, like TCP/IP in Unix, became essential.
• 1990s: Linux and Advanced GUIs
o Linux (1991) introduced open-source development.
o Windows and Mac OS refined GUIs and gained widespread adoption.
• 2000s-Present: Mobility and Cloud
o Mobile OSs like iOS (2007) and Android (2008) dominate.
o Cloud-based and virtualization technologies reshape computing, with
OSs like Windows Server and Linux driving innovation.
• AI Integration - (Ongoing)
With the growth of time, Artificial intelligence came into picture. Operating
system integrates features of AI technology like Siri, Google Assistant, and
Alexa and became more powerful and efficient in many way. These AI
features with operating system create a entire new feature like voice
commands, predictive text, and personalized recommendations.
Operating System Services
An operating system is software that acts as an intermediary between the user and
computer hardware. It is a program with the help of which we are able to run various
applications. It is the one program that is running all the time. Every computer must
have an operating system to smoothly execute other programs.
• The OS coordinates the use of hardware and application programs for users.
• It provides a platform for running application software.
• It is a set of special programs that help the computer function properly.
• It controls input–output devices and system operations.
• It manages program execution and file handling.
OS Services
1. Program Execution
The Operating System manages program execution by loading programs into memory
and scheduling them using algorithms like FCFS, SJF. It ensures smooth execution of
user and system programs while preventing deadlocks where processes wait
indefinitely. The OS also allocates system resources efficiently for proper functioning.
• Loads programs into memory for execution.
• Uses CPU scheduling algorithms (FCFS, SJF, etc.) to decide execution order.
• Handles and prevents deadlocks during execution.
• Manages system resources for efficient overall functioning.
2. Input Output Operations
The Operating System manages all input-output operations and enables
communication between users, programs, and device drivers. Device Device drivers
act as the software interface for hardware, allowing the OS to control devices
smoothly. The OS also provides programs with safe and timely access to input-output
devices whenever required.
• Manages all input-output operations.
• Communicates with hardware through device drivers.
• Ensures proper coordination between devices and the system.
• Provides programs controlled access to input-output devices.
3. Communication Between Processes
The Operating System manages communication between processes and enables
smooth data transfer among them. It handles both local communication on the same
computer and communication across networked systems. This ensures efficient and
coordinated exchange of information.
• Manages inter-process communication (IPC).
• Enables data transfer between processes.
• Supports communication across networked computers.
• Ensures secure and efficient information exchange.
4. File Management
The Operating System manages all file operations by granting programs the required
access permissions such as read-only or read-write. It allows users to create, delete,
store, and organize files across devices like, floppy disk or pen drives. The OS also
decides how data should be stored and manipulated for efficient file management.
• Grants programs file access with permissions like read-only or read-write.
• Allows users to create, delete, and organize files.
• Manages file storage across devices such as hard disks and pen drives.
• Decides how data is stored and manipulated for efficient file management.
5. Memory Management
The OS manages memory like a cricket team manager choosing players. Just as the
manager decides whether a player enters the playing 11 or 15 based on performance,
the OS checks whether a new program meets the requirements for memory. If it does,
the OS decides how much memory the program needs and loads it into an appropriate
location, preventing unnecessary memory usage.
• OS checks whether a new program meets the requirements to get memory.
• It decides how much memory the program needs.
• Loads the program into a suitable memory location.
• Prevents programs from using unnecessary or extra memory.
6. Process Management
Process management can be understood by imagining the kitchen stove as the CPU
and the chef as the Operating System. The chef must cook multiple dishes (programs)
and ensures no single dish takes too much time so that every dish gets a fair chance to
be cooked. In this way, the OS schedules and manages all programs efficiently to
keep the system running smoothly.
• CPU is like the kitchen stove where execution happens.
• OS (chef) ensures each program gets fair execution time.
• Prevents any program from occupying the CPU for too long.
• Schedules all programs efficiently to keep the system running smoothly.
7. Security and Privacy
Security
The Operating System keeps the computer safe from unauthorized users by adding
protective security layers. It defends the system from threats like viruses and hackers
through tools such as firewalls and antivirus software. These measures ensure the
safety of the computer and its data.
• Blocks unauthorized access to the system.
• Protects against viruses and malware.
• Uses firewalls and antivirus tools for defense.
• Ensures overall system and data safety.
Privacy
The Operating System helps keep personal information private, similar to locking a
door that only you can open. It ensures that sensitive files and data remain hidden
from others. In this way, the OS respects user confidentiality and protects important
information.
• Keeps personal data hidden from others.
• Provides access control options like passwords.
• Ensures only authorized users can view files.
• Protects sensitive information from misuse.
8. Resource Management
The Operating System manages how system resources are shared among different
processes. It allocates CPU time using CPU Scheduling Algorithms, handles memory
management, and controls input-output devices. By deciding which process gets
which resource, the OS ensures proper and efficient use of all available resources.
• Shares system resources among multiple processes.
• Allocates CPU time using scheduling algorithms.
• Manages memory and input-output devices.
• Ensures efficient and proper use of all resources.
9. User Interface
The Operating System provides a user interface that allows users to interact with the
system either through a command-line interface(CLI) or a Graphical User Interface
(GUI). In a CLI, the command interpreter executes user-typed commands. A GUI
offers a mouse-based window and menu system that makes interaction easier and
more visual.
• Provides both CLI and GUI for user interaction.
• CLI uses a command interpreter to run user commands.
• GUI offers windows, icons, and menus for easy use.
• Helps users communicate smoothly with the operating system.
10. Networking
This service enables communication between devices on a network by managing
connections and controlling data exchange. It allows devices to connect to the internet,
send and receive data packets, and maintain stable communication. Through proper
network management, the system ensures smooth and reliable data transfer.
• Manages network connections between devices.
• Supports internet access and communication.
• Sends and receives data packets reliably.
• Ensures smooth and stable network operations.
11. Error Handling
The Operating System detects and handles errors occurring in the CPU, memory, or
input-output devices to keep the system stable. It prevents frequent errors, avoids
deadlocks, and fixes issues that appear during program execution. A secure OS also
acts as a protective layer against external threats or breaches.
• Detects and handles CPU, memory, and I/O errors.
• Prevents frequent errors and avoids deadlocks.
• Fixes issues that occur during task execution.
• Provides security measures against external threats and breaches.
12. Time Management
Imagine a traffic light as the Operating System, guiding cars (programs) on when to
stop, wait, or move. Red represents the simple queue, yellow is the ready queue, and
green means the program is under execution. By switching lights at proper intervals,
the OS ensures all programs move smoothly without traffic or delays.
• Red light = programs waiting in the simple queue.
• Yellow light = programs in the ready queue.
• Green light = programs under execution.
• OS changes states at proper intervals to ensure smooth program flow.
System Calls
User programs cannot directly access hardware or critical OS resources because it
would make the system unstable and insecure. To maintain safety, the operating
system provides system calls — controlled interfaces that allow user programs to
request services from the kernel. These calls act as a gateway between user mode and
kernel mode. System Calls are,
• A way for programs to interact with the operating system.
• Provide the services of the operating system to the user programs.
• Only entry points into the kernel are executed in kernel mode.
System Call
Example:
• Opening a file in C (fopen) internally uses system calls like open().
• Running a program in Linux uses fork() and exec() system calls.
• Printing on screen uses the write() system call.
How do System Calls Work?
A system call is a controlled entry point that allows a user program to request a
service from the operating system. Here's how it works:
• The user program executes a system call instruction (e.g., using syscall or int 0x80).
• The CPU switches from user mode → kernel mode for safe execution.
• The kernel identifies the system call number and performs the requested operation (file
access, process creation, memory allocation, etc.).
• After completing the task, the kernel switches back to user mode.
• The result (success/failure/data) is returned to the program.
• Without system calls, every program would need its own way to access hardware, leading to
inconsistent and insecure systems.
System calls do not always cause context switching. They primarily involve a mode
switch from user mode to kernel mode. A context switch happens only when the
calling process is blocked, not during every system call.
Types of System Calls
Services provided by an OS are typically related to any kind of operation that a user
program can perform like creation, termination, forking, moving, communication, etc.
Similar types of operations are grouped into one single system call category. System
calls are classified into the following categories:
Types of system call
Layered Operating System
Layered Structure is a type of system structure in which the different services of the
operating system are split into various layers, where each layer has a specific well-
defined task to perform. It was created to improve the pre-existing structures like the
Monolithic structure ( UNIX ) and the Simple structure ( MS-DOS ). Example - The
Windows NT operating system uses this layered approach as a part of it. Design
Analysis : The whole Operating System is separated into several layers ( from 0 to n )
as the diagram shows. Each of the layers must have its own specific function to
perform. There are some rules in the implementation of the layers as follows.
1. The outermost layer must be the User Interface layer.
2. The innermost layer must be the Hardware layer.
3. A particular layer can access all the layers present below it but it cannot access the layers
present above it. That is layer n-1 can access all the layers from n-2 to 0 but it cannot access
the nth layer.
Thus if the user layer wants to interact with the hardware layer, the response will be
traveled through all the layers from n-1 to 1. Each layer must be designed and
implemented such that it will need only the services provided by the layers below it.
Layered OS Design
Advantages :
There are several advantages to this design :
1. Modularity : This design promotes modularity as each layer performs only the tasks it is
scheduled to perform.
2. Easy debugging : As the layers are discrete so it is very easy to debug. Suppose an error
occurs in the CPU scheduling layer, so the developer can only search that particular layer to
debug, unlike the Monolithic system in which all the services are present together.
3. Easy update : A modification made in a particular layer will not affect the other layers.
4. No direct access to hardware : The hardware layer is the innermost layer present in the
design. So a user can use the services of hardware but cannot directly modify or access it,
unlike the Simple system in which the user had direct access to the hardware.
5. Abstraction : Every layer is concerned with its own functions. So the functions and
implementations of the other layers are abstract to it.
Disadvantages :
Though this system has several advantages over the Monolithic and Simple design,
there are also some disadvantages as follows.
1. Complex and careful implementation : As a layer can access the services of the layers below
it, so the arrangement of the layers must be done carefully. For example, the backing storage
layer uses the services of the memory management layer. So it must be kept below the
memory management layer. Thus with great modularity comes complex implementation.
2. Slower in execution : If a layer wants to interact with another layer, it sends a request that
has to travel through all the layers present in between the two interacting layers. Thus it
increases response time, unlike the Monolithic system which is faster than this. Thus an
increase in the number of layers may lead to a very inefficient design.
Monolithic Architecture in OS
The monolithic operating system is a very simple operating system where the kernel
directly controls device management, memory management, file management, and
process management. All of the system's resources are accessible to the kernel. Every
part of the operating system is contained within the kernel in monolithic systems.
MicroKernel
Microkernel is a type of Operating System that provides some basic services for an
operating system/ These services include memory management, process scheduling,
etc. Some other services like Device Drivers, File Systems, etc are managed by user-
level processes. User Level Process communicates with Microkernel via message
passing. This way of handling the process makes microkernels more modular and
more flexible than traditional monolithic kernels.
Virtual Machines in Operating System
A Virtual Machine (VM) is a software-based computer that runs within a physical
computer (known as the host). It emulates the behavior of a physical machine and can
run its own operating system (guest OS) and applications independently just like a
real computer.
For example, you can run a Linux VM inside a Windows PC using tools like
VirtualBox or VMware.
Working of Virtual Machines
A VM uses virtualization technology to abstract the hardware of a physical machine
(CPU, memory, storage, etc.) into a virtual environment. This is managed by a special
software called a hypervisor, which allocates system resources to multiple VMs.
Each VM behaves like a separate computer, even though it's running on shared
hardware. It includes:
• Virtual CPU
• Virtual memory
• Virtual disk (storage)
• Network interface card (NIC)
Example: When you run multiple processes on a regular OS, they appear to have
separate CPUs and memory (thanks to CPU scheduling and virtual memory). A VM
extends this illusion to the OS level itself.
Virtual Machines Diagram
Types of Virtual Machines
There are two main types of VMs:
1. Process Virtual Machine
• Designed to run a single application (or process).
• Example: Java Virtual Machine (JVM), which allows Java programs to run on any platform.
2. System Virtual Machine
• Emulates an entire physical machine.
• Can run a full OS like Linux, Windows, or macOS.
• Example: VMs created using VirtualBox, VMware, or Hyper-V.
Process in Operating System
A process is a program in execution. For example, when we write a program in C or
C++ and compile it, the compiler creates binary code. The original code and binary
code are both programs. When we actually run the binary code, it becomes a process.
A process is an 'active' entity instead of a program, which is considered a 'passive'
entity.
A single program can create many processes when run multiple times; for example,
when we open a .exe or binary file multiple times, multiple instances begin (multiple
processes are created).
How Does a Process Look Like in Memory?
A process in memory is divided into several distinct sections, each serving a different
purpose. Here's how a process typically looks in memory.
Process structure
• Text Section: A text or code segment contains executable instructions. It is
typically a read only section
• Stack: The stack contains temporary data, such as function parameters,
returns addresses, and local variables.
• Data Section: Contains the global variable.
• Heap Section: Dynamically memory allocated to process during its run time.
Attributes of a Process
A process has several important attributes that help the operating system manage and
control it. These attributes are stored in a structure called the Process Control Block
(PCB) (sometimes called a task control block). The PCB keeps all the key information
about the process, including:
1. Process ID (PID): A unique number assigned to each process so the operating
system can identify it.
2. Process State: This shows the current status of the process, like whether it is
running, waiting, or ready to execute.
3. Priority and other CPU Scheduling Information: Data that helps the
operating system decide which process should run next, like priority levels
and pointers to scheduling queues.
4. I/O Information: Information about input/output devices the process is using.
5. File Descriptors: Information about open files and network connections.
6. Accounting Information: Tracks how long the process has run, the amount of
CPU time used, and other resource usage data.
7. Memory Management Information: Details about the memory space
allocated to the process, including where it is loaded in memory and the
structure of its memory layout (stack, heap, etc.).
These attributes in the PCB help the operating system control, schedule, and manage
each process effectively.
Key Types of Relationships
Parent-Child (Process Tree):
1) A parent process creates child processes (e.g., using fork), forming a hierarchy.
2) Children often inherit resources or copy the parent's state but have their own PCB
and PID.
3) They communicate and synchronize, with the parent often waiting for children to
finish (e.g., wait()).
Cooperating Processes:
• Processes that need to share data or synchronize activities.
• They become "independent" if they don't share resources but can be
"cooperating" if they do.
· Sibling Processes:
• Processes created by the same parent, often working together on related tasks.
· Independent Processes:
• Processes with separate memory spaces and resources, communicating only
via explicit OS mechanisms.
What is a Process Control Block(PCB)?
A Process Control Block (PCB) is a data structure that is used by an Operating
System to manage and regulate how processes are carried out. In operating systems,
managing the process and scheduling them properly play the most significant role in
the efficient usage of memory and other system resources. In the process control
block, all the details regarding the process corresponding to it like its current status,
its program counter, its memory use, its open files, and details about CPU scheduling
are stored.
Different States of a Process
A process is a program in execution and it is more than a program code called as text
section and this concept works under all the operating system because all the task
perform by the operating system needs a process to perform the task
The process executes when it changes the state. The state of a process is defined by
the current activity of the process.
Each process may be in any one of the following states −
New − The process is being created.
Running − In this state the instructions are being executed.
Waiting − The process is in waiting state until an event occurs like I/O operation
completion or receiving a signal.
Ready − The process is waiting to be assigned to a processor.
Terminated − the process has finished execution.
It is important to know that only one process can be running on any processor at any
instant. Many processes may be ready and waiting.
Now let us see the state diagram of these process states −
Explanation
Step 1 − Whenever a new process is created, it is admitted into ready state.
Step 2 − If no other process is present at running state, it is dispatched to running
based on scheduler dispatcher.
Step 3 − If any higher priority process is ready, the uncompleted process will be sent
to the waiting state from the running state.
Step 4 − Whenever I/O or event is completed the process will send back to ready state
based on the interrupt signal given by the running state.
Step 5 − Whenever the execution of a process is completed in running state, it will
exit to terminate state, which is the completion of process.
Process State Transitions
Process state transitions describe how a process moves between states (New, Ready,
Running, Blocked/Waiting, Terminated) in an operating system, triggered by events
like dispatching to CPU, I/O requests, preemption, or completion, managed by the
scheduler to efficiently use resources.
Key State Transitions
• New -> Ready: Process loaded into memory.
• Ready -> Running: Scheduler assigns CPU.
• Running -> Blocked/Waiting: Process requests I/O or resource.
• Blocked/Waiting -> Ready: Event/I/O completes, process becomes runnable.
• Running -> Ready (Preemption): Time slice expires or higher priority process
arrives.
• Running -> Terminated: Process finishes or is killed.
Context Switching in Operating System
Context switching is the process where the CPU stops running one process, saves its
current state, and loads the saved state of another process so that multiple processes
can share the CPU effectively.
Need in Multitasking
It is essential in multitasking systems where many processes need CPU time.
• In multitasking, the CPU keeps switching between processes.
• This makes it seem like processes are running at the same time, even though
the CPU works on one process at a time.
• Without context switching, one process could monopolize the CPU, and others
would have to wait indefinitely
Role in Scheduling
• The scheduler decides which process should run next based on a scheduling
algorithm (like Round Robin, Priority Scheduling, etc.).
• Context switching executes that decision by stopping the current process and
starting the chosen one.
• The dispatcher is the component that actually performs the switch.
Context Switching Triggers
Context Switching Happen:
• When a high-priority process comes to a ready state (i.e. with higher priority
than the running process).
• An Interrupt occurs.
• User and kernel-mode switch (It is not necessary though)
• Preemptive CPU scheduling is used.
When switching between user mode and kernel/user mode is necessary, operating
systems use the kernel/user switch.
Working Process of Context Switching
Let us take examples of two processes po and p1 that execute in interleaved manner
State Diagram of Context Switching
Explanation of the Above Diagram
The diagram illustrates how the CPU alternates execution between two processes —
p0 and p1 — through context switching.
1. Execution Phase (Process p0)
• Process p0 is running while p1 remains idle.
• At some point, an interrupt or system call occurs (e.g., a timer interrupt or I/O
completion).
2. Saving Current State (p0 → PCB0)
• The operating system pauses p0.
• The current state of p0 (register values, program counter, etc.) is saved into its
Process Control Block (PCB0).
• This ensures that p0 can later resume exactly where it left off.
3. Loading New Process State (PCB1 → p1)
• The OS retrieves the saved state of p1 from PCB1.
• This step restores p1’s CPU context so it can continue execution from its last
saved point.
4. Execution Phase (Process p1)
• Now, p1 is running while p0 is idle.
• Another interrupt or system call occurs, triggering another switch.
5. Saving State of p1 (p1 → PCB1): The OS saves the current state of p1 into PCB1.
6. Reloading State of p0 (PCB0 → p0)
• The saved state of p0 from PCB0 is loaded back into the CPU registers.
• p0 resumes execution right where it left off.
Overhead
• Time spent switching is called context switch overhead.
• During this time, the CPU is not performing actual process work it’s just
preparing to run the next process.
• If context switching happens too often, CPU efficiency drops.
Foundations of Process Scheduling (Operating Systems)
Process scheduling is a core function of an operating system. It decides which
process gets the CPU, when, and for how long, so that the system runs efficiently
and fairly.
Why Process Scheduling is Needed
• The CPU is a limited resource
• Multiple processes compete for CPU time
• Scheduling ensures:
Better CPU utilization
Faster response time
Fairness among processes
Efficient multitasking
Process States (Scheduling Context)
A process typically moves through these states:
New – Process is being created
Ready – Waiting for CPU
Running – Currently executing on CPU
Waiting / Blocked – Waiting for I/O or an event
Terminated – Execution finished
Scheduling Queues
Job Queue – All processes in the system
Ready Queue – Processes ready to execute
Waiting Queue – Processes waiting for I/O
CPU Scheduler
The CPU scheduler selects one process from the ready queue and allocates the CPU
to it.
Scheduling Criteria
Schedulers are designed to optimize:
CPU utilization
Throughput
Turnaround time
Waiting time
Response time
Fairness
1. CPU Utilization
It refers to the percentage of time the CPU is busy executing processes.
Higher CPU utilization is desirable
Aim: Keep the CPU as busy as possible
2. Throughput
It is the number of processes completed per unit time.
Measured in processes/second
Higher throughput means better system performance
3. Turnaround Time
It is the total time taken by a process from submission to completion.
Turnaround Time=Completion Time−Arrival Time
Includes waiting, execution, and I/O time
Lower turnaround time is preferred
4. Waiting Time
It is the total time a process spends waiting in the ready queue.
Waiting Time=Turnaround Time−Burst Time
Does not include execution time
Lower waiting time improves user satisfaction
5. Response Time
It is the time between submitting a process and receiving the first response.
Response Time=First CPU Allocation Time−Arrival Time
Important for interactive systems
Lower response time gives faster feedback to users
6. Fairness
It ensures that every process gets a fair share of the CPU.
Prevents starvation
No process should wait indefinitely
Dispatcher
The dispatcher gives control of the CPU to the selected process. It involves:
Context switching
Switching to user mode
Jumping to the process’s instruction
Process scheduling is the activity of the process manager that handles the removal of
the running process from the CPU and the selection of another process based on a
particular strategy. Throughout its lifetime, a process moves between various
scheduling queues, such as the ready queue, waiting queue or devices queue.
• Scheduling is important in operating systems with multiprogramming as
multiple processes might be eligible for running at a time.
• One of the key responsibilities of an Operating System (OS) is to decide
which programs will execute on the CPU.
• Process Schedulers are fundamental components of operating systems
responsible for deciding the order in which processes are executed by the CPU.
In simpler terms, they manage how the CPU allocates its time among multiple
tasks or processes that are competing for its attention.
Types of Scheduling Queues
Process Queues play an important role in process scheduling.
Job Queue (In Disk)
This queue is known as the job queue, it contains all the processes or jobs in the list
that are waiting to be processed. Job: When a job is created, it goes into the job queue
and waits until it is ready for processing.
• Contains all submitted jobs.
• Processes are stored here in a wait state until they are ready to go to the
execution stage.
• This is the first and most basic state that acts as a default storage of new jobs
added to a scheduling system.
• Long Term Scheduler Picks a process from Job Queue and moves to ready
queue.
Ready Queue (In Main Memory)
The Stand-by queue contains all the processes ready to be fetched from the memory,
for execution. When the process is initiated, it joins the ready queue to wait for the
CPU to be free. The operating system assigns a process to the executing processor
from this queue based on the scheduling algorithm it implements.
• Contains processes (mainly their PCBs) waiting for the CPU to execute various
processes it contains.
• They are controlled using a scheduling algorithm like FCFS, SJF, or Priority
Scheduling.
• Short Term Scheduler picks a process from Ready Queue and moves the
selected process to running state.
Block or Device Queues (In Main Memory)
The processes which are blocked due to unavailability of an I/O device are added to
this queue. Every device has its own block queue.
Flow of Movement in the above Queues
The below diagram shows movements of processes in different queues.
Process Schedulers
Process Schedulers are fundamental components of operating systems responsible for
deciding the order in which processes are executed by the CPU. In simpler terms, they
manage how the CPU allocates its time among multiple tasks or processes that are
competing for its attention.
1. Long-Term Scheduler (Job Scheduler)
The Long-Term Scheduler is responsible for loading processes from disk into main
memory so they can begin execution.
• Transfers processes from the Job Queue to the Ready Queue.
• Controls the degree of Multi-programming — the number of processes present
in memory or ready state at any time.
• Carefully selects a balanced mix of I/O-bound and CPU-bound processes to
ensure efficient system performance.
• Helps avoid a situation where either the CPU or I/O devices remain idle.
• In many modern time-sharing systems (such as Windows), a long-term
scheduler may not exist; new processes are directly admitted to memory for
short-term scheduling.
• It is the slowest among all schedulers, as it operates less frequently.
2. Short-Term Scheduler (CPU Scheduler)
The Short-Term Scheduler (STS) is responsible for selecting a process from the ready
queue and assigning the CPU to it.
• Frequently selects the next process to execute from the ready state.
• Ensures no process suffers from starvation.
• Uses various CPU scheduling algorithms to decide process order.
• Maximizes CPU utilization by keeping the processor as busy as possible.
• Calls the dispatcher, which performs the actual context switch.
• It is the fastest scheduler, since it operates very frequently (often every few
milliseconds).
• The dispatcher is responsible for loading the process selected by the Short-
term scheduler on the CPU (Ready to Running State). Context switching is
done by the dispatcher only. A dispatcher does the following work:
• Saving context (process control block) of previously running process if not
finished.
• Switching system mode to user mode.
• Jumping to the proper location in the newly loaded program.
3. Medium-Term Scheduler
The Medium-Term Scheduler (MTS) manages swapping, which temporarily moves
processes between main memory and disk.
• Swaps processes out of memory when they are waiting (e.g., blocked for I/O)
to reduce the degree of multiprogramming.
• Frees memory for other active processes.
• Swaps processes back into memory when they are ready to continue execution,
allowing them to resume from where they left off.
• Helps maintain an effective mix of CPU-bound and I/O-bound processes.
• It operates faster than the long-term scheduler but slower than the short-term
scheduler.
Preemptive and Non-Preemptive
Scheduling
CPU scheduling in operating systems is the method of selecting which process in the
ready queue will execute on the CPU next. It aims to utilise the processor efficiently
while minimising waiting and response times. By determining an optimal execution
order, CPU scheduling enhances overall system performance, supports smooth
multitasking, and improves the user experience.
Scheduling can be broadly classified into two types: Preemptive and Non-Preemptive.
Preemptive Scheduling vs Non-Preemptive Scheduling
• Preemptive Scheduling: After P1 goes for I/O, P2
comes into the CPU and utilizes it.
• Non-Preemptive Scheduling: After P1 goes for I/O,
the CPU remains idle until P1 finishes I/O and
comes back.
Preemptive Scheduling
In preemptive scheduling, the operating system can interrupt a running process to
allocate the CPU to another process usually due to priority rules or time-sharing
policies. A process may be moved from Running → Ready state before it finishes.
In the following example P2 is preempted at time 1 due to
arrival of a higher priority process.
Non-Preemptive Scheduling
In non-preemptive scheduling, once a process starts using the CPU, it runs until it
finishes or moves to a waiting state. The OS cannot forcibly take away the CPU.
Below is the table and Gantt Chart according to the First
Come First Serve (FCFS) Algorithm: We can notice that
every process finishes execution once it gets CPU.
CPU Scheduling Algorithms
FCFS - First Come First Serve CPU Scheduling
First Come, First Serve (FCFS) is one of the simplest types of CPU scheduling
algorithms. It is exactly what it sounds like: processes are attended to in the order in
which they arrive in the ready queue, much like customers lining up at a grocery store.
FCFS Scheduling is a non-preemptive algorithm, meaning once a process starts
running, it cannot be stopped until it voluntarily relinquishes the CPU, typically when
it terminates or performs I/O. This method schedules processes in the order they
arrive, without considering priority or other factors.
Example of FCFS CPU Scheduling:
To understand the First Come, First Served (FCFS) scheduling algorithm effectively,
we'll use two examples -
• one where all processes arrive at the same time,
• another where processes arrive at different times.
We'll create Gantt charts for both scenarios and calculate the turnaround time and
waiting time for each process.
Scenario 1: Processes with Same Arrival Time
Consider the following table of arrival time and burst time for three processes P1, P2
and P3
Process Arrival Time Burst Time
p1 0 5
p2 0 3
p3 0 8
Turnaround Time = Completion Time - Arrival Time
Waiting Time = Turnaround Time - Burst Time
Processes AT BT CT TAT WT
P1 0 5 5 5-0 = 5 5-5 = 0
P2 0 3 8 8-0 = 8 8-3 = 5
P3 0 8 16 16-0 = 16 16-8 = 8
• Average Turn around time = 9.67
• Average waiting time = 4.33
Scenario 2: Processes with Different Arrival Times
Consider the following table of arrival time and burst time for three processes P1, P2
and P3
Process Burst Time (BT) Arrival Time (AT)
P1 5 ms 2 ms
P2 3 ms 0 ms
P3 4 ms 4 ms
Completion Time Turnaround Time (TAT = Waiting Time (WT =
rocess
(CT) CT - AT) TAT - BT)
P2 3 ms 3 ms 0 ms
P1 8 ms 6 ms 1 ms
P3 12 ms 8 ms 4 ms
• Average Turnaround time = 5.67
• Average waiting time = 1.67
Shortest Job First or SJF CPU Scheduling
Shortest Job First (SJF) or Shortest Job Next (SJN) is a scheduling process that selects
the waiting process with the smallest execution time to execute next. This scheduling
method may or may not be preemptive. Significantly reduces the average waiting time
for other processes waiting to be executed.
Example: Consider the following table of arrival time and burst time for three
processes P1, P2 and P3.
Process Burst Time Arrival Time
P1 6 ms 0 ms
P2 8 ms 2 ms
P3 3 ms 4 ms
Arrival Burst Completion Turn Around Waiting Time
Process Time Time
(AT) (BT) Time (CT) Time (TAT) (WT)
P1 0 6 6 6-0 = 6 6-6 = 0
P2 2 8 17 17-2 = 15 15-8 = 7
P3 4 3 9 9-4 = 5 5-3 = 2
• Average Turn around time = (6 + 15 + 5)/3 = 8.6 ms
• Average waiting time = ( 2 + 0 + 7 )/3 = 9/3 = 3 ms
Round Robin Scheduling in Operating System
Round Robin Scheduling is a method used by operating systems to manage the
execution time of multiple processes that are competing for CPU attention. It is called
"round robin" because the system rotates through all the processes, allocating each of
them a fixed time slice or "quantum", regardless of their priority.
The primary goal of this scheduling method is to ensure that all processes are given an
equal opportunity to execute, promoting fairness among tasks.
Scenario 1: Processes with Same Arrival Time
Consider the following table of arrival time and burst time for three processes P1, P2
and P3 and given Time Quantum = 2 ms
Process Burst Time Arrival Time
P1 4 ms 0 ms
P2 5 ms 0 ms
P3 3 ms 0 ms
Processes AT BT CT TAT WT
P1 0 4 8 8-0 = 8 8-4 = 4
P2 0 5 12 12-0 = 12 12-5 = 7
P3 0 3 11 11-0 = 11 11-3 = 8
• Average Turn around time = (8 + 12 + 11)/3 = 31/3 = 10.33 ms
• Average waiting time = (4 + 7 + 8)/3 = 19/3 = 6.33 ms
Scenario 2: Processes with Different Arrival Times
Consider the following table of arrival time and burst time for three processes P1, P2
and P3 and given Time Quantum = 2
Process Burst Time (BT) Arrival Time (AT)
P1 5 ms 0 ms
P2 2 ms 4 ms
P3 4 ms 5 ms
Completion Time Turnaround Time (TAT = Waiting Time (WT =
Process
(CT) CT - AT) TAT - BT)
P1 7 ms 7 ms 2 ms
P2 6 ms 2 ms 0 ms
P3 11 ms 6 ms 2 ms
• Average Turn around time =7+2+6/3=15/3=5ms
• Average waiting time = 2+0+2/3=1.33ms
Priority Scheduling in Operating System
Priority scheduling is one of the most common scheduling algorithms used by the
operating system to schedule processes based on their priority. Each process is
assigned a priority value based on criteria such as memory requirements, time
requirements, other resource needs, or the ratio of average I/O to average CPU burst
time.
The process with the highest priority is selected for execution first. If there are
multiple processes sharing the same priority, they are scheduled in the order they
arrived, following a First-Come, First-Served approach. The chosen process is then
executed, either until completion or until it is preempted, depending on whether the
scheduling is preemptive or non-preemptive.
Priority Scheduling can be implemented in two ways:
• Non-Preemptive Priority Scheduling
• Preemptive Priority Scheduling
Non-Preemptive Priority Scheduling
In Non-Preemptive Priority Scheduling, the CPU is not taken away from the running
process. Even if a higher-priority process arrives, the currently running process will
complete first.
Ex: A high-priority process must wait until the currently running process finishes.
Example of Non-Preemptive Priority Scheduling:
Consider the following table of arrival time and burst time for three processes P1, P2
and P3:
Note: Lower number represents higher priority.
Process Arrival Time Burst Time Priority
P1 0 4 2
P2 1 2 1
P3 2 6 3
Arrival Burst Completion Turnaround Time Waiting Time
Process
Time Time Time (CT - AT) (TAT - BT)
P1 0 4 4 4 0
P2 1 2 6 5 3
P3 2 6 12 10 4
• Average Turnaround Time = 6.33
• Average Waiting Time = 2.33
Preemptive Priority Scheduling
In Preemptive Priority Scheduling, the CPU can be taken away from the currently
running process if a new process with a higher priority arrives.
Ex: A low-priority process is running, and a high-priority process arrives; the CPU
immediately switches to the high-priority process.
Example of Preemptive Priority Scheduling (Same Arrival Time)
Consider the following table of arrival time and burst time for three processes P1, P2
and P3:
Note: Higher number represents higher priority.
Process Arrival Time Burst Time Priority
P1 0 7 2
P2 0 4 1
P3 0 6 3
Arrival Burst Completion Turnaround Time Waiting Time
Process
Time Time Time (CT - AT) (TAT - BT)
P1 0 7 13 13 6
P2 0 4 17 17 13
P3 0 6 6 6 0
• Average Turnaround Time = 12
• Average Waiting Time = 6.33
Example of Preemptive Priority Scheduling (Different Arrival
Time)
Consider the following table of arrival time and burst time for three processes P1, P2
and P3:
Process Arrival Time Burst Time Priority
P1 0 6 2
P2 1 4 3
P3 2 5 1
Arrival Burst Completion Turnaround Time Waiting Time
Process
Time Time Time (CT - AT) (TAT - BT)
P1 0 6 10 10 4
P2 1 4 5 4 0
P3 2 5 15 13 8
• Average Turnaround Time = 9
• Average Waiting Time = 4
Multiple-Processor Scheduling in Operating System
CPU Scheduling is a mechanism by which an operating system decides which task or
process should execute on the CPU at any given moment. When a system contains
more than one CPU, Multiple-Processor Scheduling involves distributing tasks across
multiple processors. This enables several tasks to be processed in parallel, improving
performance significantly.
Key Challenges:
• Deciding which CPU handles which task.
• Balancing workloads between processors to avoid idle CPUs or overloaded
processors.
Approaches to Multiple-Processor Scheduling
Asymmetric Multiprocessing (AMP)
• One processor acts as a Master Server handling scheduling decisions and I/O
operations.
• Other processors execute only user code.
• Simple design, reduces data-sharing complexity.
Symmetric Multiprocessing (SMP)
• Each processor can schedule tasks independently.
• Two models of task queues:
Common Ready Queue: All CPUs access a shared queue of ready
processes.
Private Ready Queues: Each CPU has its own queue of ready
processes.
Real Time Scheduling in Operating System
Real-time scheduling in operating systems ensures tasks are completed within strict
timing constraints (deadlines) to guarantee system reliability, often using preemptive,
priority-based algorithms. It prioritizes determinism and immediate response over
fairness, with key approaches including Rate Monotonic (fixed-priority) and Earliest
Deadline First (dynamic-priority).
Key Concepts in Real-Time Scheduling
• Hard Real-Time: Strict deadlines must be met; failure results in system failure
(e.g., flight control, airbags).
• Soft Real-Time: Deadlines are desirable, but occasional misses are acceptable
(e.g., video streaming)
Common Scheduling Algorithms
Rate Monotonic Scheduling (RMS): A fixed-priority algorithm where shorter-
period tasks get higher priority.
Earliest Deadline First (EDF): A dynamic-priority algorithm that schedules the task
with the closest deadline first.
Thread in Operating System
A thread is a single sequence stream within a process. Threads are also called
lightweight processes as they possess some of the properties of processes. Each
thread belongs to exactly one process.
• In an operating system that supports multithreading, a process can consist of
many threads.
• All threads belonging to the same process share code section, data section,
and OS resources (e.g. open files and signals), but each thread has its own
(thread control block) - thread ID, program counter, register set, and a stack.
Why Do We Need Threads (and Their Benefits)
Threads are needed in modern operating systems and applications because they:
• Improve Application Performance: Threads can run in parallel, making
programs execute faster.
• Increase Responsiveness: Even if one thread is busy, another can return
results or handle user actions immediately.
• Enable Concurrency: Multiple things can happen at once, such as background
saving, formatting, and user input in Microsoft Word or Google Docs.
• Simplify Communication: Since threads share the same memory space, they
can directly exchange data without special inter-process communication
mechanisms.
• Support Prioritization: Like processes, threads can have priorities; the
highest-priority thread gets scheduled first.
• Efficient Context Switching: Switching between threads takes less time than
switching between processes because threads use the same address space.
• Better Multiprocessor Utilization: Threads from the same process can run on
different processors simultaneously, speeding up execution.
• Resource Sharing: Threads within a process share code, data, and files, which
saves resources.
• Higher Throughput: Dividing a process into multiple threads allows more jobs
to finish per unit time.
• Synchronization Support: Since threads share resources, synchronization
tools (locks, semaphores, etc.) ensure safe access to shared data.
• Thread Management: Each thread has a Thread Control Block (TCB) that
stores its state, register values, and scheduling info for context switching.
Types of Thread in Operating System
Threads are of two types. These are described below.
• User Level Thread
• Kernel Level Thread
Threads
User-Level Threads (ULTs)
• Managed entirely in user space using a thread library; the kernel is unaware
of them.
• Switching between ULTs is fast since only program counter, registers, and
stack need to be saved/restored.
• Do not require system calls for creation or management, making them
lightweight.
• Blocking Limitation: If one thread makes a blocking system call, the entire
process (all threads) is blocked.
• Scheduling is done by the application itself, which may not be as efficient as
kernel-level scheduling.
• Cannot fully utilize multiprocessor systems because the kernel schedules
processes, not individual user-level threads.
Kernel-Level Threads (KLTs)
• Managed directly by the operating system kernel; each thread has an entry in
the kernel’s thread table.
• The kernel schedules each thread independently, allowing true parallel
execution on multiple CPUs/cores.
• Handles blocking system calls efficiently; if one thread blocks, the kernel can
run another thread from the same process.
• Provides better load balancing across processors since the kernel controls all
threads.
• Context switching is slower compared to ULTs because it requires switching
between user mode and kernel mode.
• Implementation is more complex and requires frequent interaction with the
kernel.
• Large numbers of threads may add extra load on the kernel scheduler,
potentially affecting performance.
Difference Between Process and Thread
The primary difference is that threads within the same process run in a shared
memory space, while processes run in separate memory spaces. Threads are not
independent of one another like processes are, and as a result, threads share with other
threads their code section, data section, and OS resources (like open files and signals).
But, like a process, a thread has its own program counter (PC), register set, and stack
space.
Thread States in Operating Systems
When a thread moves through the system, it is always in one of the five states:
(1) Ready(2) Running(3) Waiting(4) Delayed(5) Blocked
Excluding CREATION and FINISHED state.
1. When an application is to be processed, then it creates a thread.
2. It is then allocated the required resources(such as a network) and it comes in
the READY queue.
3. When the thread scheduler (like a process scheduler) assign the thread with
processor, it comes in RUNNING queue.
4. When the process needs some other event to be triggered, which is outsides
it's control (like another process to be completed), it transitions from
RUNNING to WAITING queue.
5. When the application has the capability to delay the processing of the thread,
it when needed can delay the thread and put it to sleep for a specific amount
of time. The thread then transitions from RUNNING to DELAYED queue. An
example of delaying of thread is snoozing of an alarm. After it rings for the
first time and is not switched off by the user, it rings again after a specific
amount of time. During that time, the thread is put to sleep.
6. When thread generates an I/O request and cannot move further till it's done,
it transitions from RUNNING to BLOCKED queue.
7. After the process is completed, the thread transitions from RUNNING to
FINISHED.
The difference between the WAITING and BLOCKED transition is that in
WAITING the thread waits for the signal from another thread or waits for another
process to be completed, meaning the burst time is specific. While, in BLOCKED
state, there is no specified time (it depends on the user when to give an input). In
order to execute all the processes successfully, the processor needs to maintain the
information about each thread through Thread Control Blocks (TCB).
Multithreading in OS
Multithreading is a technique where a process is divided into smaller execution units
called threads that run concurrently.
• A thread is also called a lightweight process. Concurrency or Parallelism
within a process is achieved by dividing a process into multiple threads.
• Multithreading improves system performance and responsiveness by
allowing multiple threads to share CPU, memory and I/O resources of a single
process.
• Example: In a browser, each tab can be a thread. In MS Word, one thread
formats text while another processes inputs.
Inter Process Communication (IPC)
Inter-Process Communication or IPC is a mechanism that allows processes to
communicate and share data with each other while they are running. Since each
process has its own memory space, IPC provides controlled methods for exchanging
information and coordinating actions. It helps processes work together efficiently and
safely in an operating system.
• It helps processes synchronize their activities, share information and avoid conflicts while
accessing shared resources.
• There are two method of IPC, shared memory and message passing. An operating system can
implement both methods of communication.
Example: A simple example of IPC is a bank ATM system, where one process reads
the card and PIN, another checks the account balance, and a third dispenses cash.
These processes communicate and coordinate to complete the transaction correctly.
Shared Memory
Communication between processes using shared memory requires processes to share
some variable and it completely depends on how the programmer will implement it.
Processes can use shared memory for extracting information as a record from another
process as well as for delivering any specific information to other processes.
Shared Memory
• In the above shared memory model, a common memory space is allocated by the kernel.
• Process A writes data into the shared memory region (Step 1).
• Process B can then directly read this data from the same shared memory region (Step 2).
• Since both processes access the same memory segment, this method is fast but requires
synchronization mechanisms (like semaphores) to avoid conflicts when multiple processes
read/write simultaneously.
• Example: Multiple people can edit the document at the same time in shared google doc.
Message Passing
Message Passing is a method where processes communicate by sending and receiving
messages to exchange data. One process sends a message and the other process
receives it, allowing them to share information. Message Passing can be achieved
through different methods like Sockets, Message Queues or Pipes.
Message Passing
• In the above message passing model, processes exchange information by
sending and receiving messages through the kernel.
• Process A sends a message to the kernel (Step 1).
• The kernel then delivers the message to Process B (Step 2).
• Here, processes do not share memory directly. Instead, communication
happens via system calls (send(), recv(), or similar).
• This method is simpler and safer than shared memory because there’s no risk
of overwriting shared data, but it incurs more overhead due to kernel
involvement.
• Example: Multiple people send updates to a group chat, but each message
goes through the server before others see it, like processes sending messages
instead of directly sharing memory.
Problems in Inter-Process Communication (IPC):
Inter-Process Communication (IPC) faces challenges when multiple processes share
resources. Improper synchronization can cause race conditions, deadlock, and
starvation, while shared data may suffer data inconsistency. IPC also adds overhead
and can raise security issues. Managing many processes can lead to scalability
problems.
Some common classical IPC problem are:
Dining Philosophers Problem
This problem illustrates deadlock and starvation. The Dining Philosophers Problem
involves five philosophers sitting around a table, each needing two forks (shared
resources) to eat. If all philosophers pick up one fork at the same time, none can eat,
resulting in deadlock.
Solution
• Use semaphores or monitors to control access to forks.
• Allow only one philosopher to pick forks at a time or limit eating to four philosophers.
• Enforce an order of picking forks to avoid circular wait.
• Prevents deadlock and starvation.
Producer–Consumer Problem
This problem deals with synchronization and buffer management. The Producer–Consumer Problem
describes producers generating data and placing it in a shared buffer, while consumers remove data
from it. The main challenge is preventing producers from adding data to a full buffer and consumers
from removing data from an empty buffer.
Solution
• Use mutex to ensure mutual exclusion on the shared buffer.
• Use counting semaphores to track empty and full buffer slots.
• Producer waits if buffer is full; consumer waits if buffer is empty.
• Ensures proper synchronization and data consistency.
Readers–Writers Problem
This problem focuses on concurrent access to shared data. The Readers–Writers
Problem allows multiple readers to read data simultaneously, while writers require
exclusive access. The challenge is avoiding starvation of either readers or writers.
Solution
• Use reader–writer locks or semaphores.
• Allow multiple readers to read simultaneously.
• Grant writers exclusive access to shared data.
• Apply priority rules to avoid starvation.
Race condition
A race condition occurs when two or more processes or threads access and modify the
same data at the same time, and the final result depends on the order in which they run.
Without proper coordination, this can lead to incorrect or unpredictable results. For
example, if two people update the same bank account simultaneously without
checking each other’s changes, the final balance may be wrong.
Causes of Race Conditions
• Simultaneous Access: when two or more processes try to read or write the same shared
resource at the same time.
• Non-Atomic Updates: Operations like increment or decrement are not indivisible.
• Lack of Synchronization: No mechanisms like locks, semaphores, or monitors are used to
control access.
• Improper Scheduling: OS scheduler interrupts processes at critical moments.
Example: Two Processes Updating a Shared
Variable
Let’s take a shared variable balance = 100 and two processes P1 and P2:
• P1 wants to add 10 to balance.
• P2 wants to subtract 10 from balance.
Race Condition
Explanation:
• P1 reads balance = 100 and prepares to add 10.
• Before P1 updates the balance with the new value (110), it is interrupted by the process P2.
• P2, unaware of P1’s action (of adding 10), reads the balance as 100 (incorrect) and prepares
to subtract 10.
• After subtracting, P2 updates the balance to 90 and then P1 resumes and writes the balance
as 110 which is incorrect now.
In many cases, the final balance may incorrectly be 110 or 90, instead of the expected
100. This is a classic race condition.
Effects of Race Conditions
• Data Corruption: Shared data may become inconsistent.
• Unpredictable Behavior: The output may vary every time the program runs.
• Security Risks: Race conditions can be exploited, e.g., in banking transactions or
authentication bypass.
• System Crashes: Critical system data may get corrupted, leading to failures.
Critical Section
The part of the program where shared resources are accessed is called the critical
section.
To avoid race condition:
Only one process at a time should enter the critical section.
Prevention Techniques
1. Mutex (Mutual Exclusion): Ensure only one process can enter the critical section at a time.
2. Semaphores: Counting or binary semaphores control access to resources.
3. Monitors: High-level synchronization constructs that manage shared resources.
4. Atomic Operations: Use hardware or software-supported atomic instructions.
5. Disable Interrupts (for kernel-level programming): Prevent context switches during critical
sections.
6. Proper Scheduling: Ensure the scheduler does not preempt critical section execution.
[Link] (Mutual Exclusion)
A Mutex is a locking mechanism that allows only one thread/process to access the
critical section at a time.
How It Works:
Before entering the critical section → thread locks the mutex.
After finishing → thread unlocks the mutex.
If another thread tries to lock it while already locked → it must wait.
2️⃣ Semaphore
A Semaphore is a signaling mechanism used to control access to shared resources.
Types of Semaphore:
(a) Binary Semaphore
Value = 0 or 1
Works similar to mutex
(b) Counting Semaphore
Value ≥ 0
Used when multiple instances of a resource are available
Operations:
wait() → decreases value
signal() → increases value
3️⃣ Monitors
A Monitor is a high-level synchronization construct that ensures only one thread
can execute inside the monitor at a time.
It combines:
Shared data
Procedures
Synchronization mechanism
Features:
Automatically provides mutual exclusion
Uses condition variables for waiting and signaling
4 Event Counters
An Event Counter is a synchronization mechanism used to coordinate processes and
prevent race conditions in the critical section problem.
It is mainly used in process synchronization to ensure proper ordering of events
between processes.
Basic Idea
An event counter is a shared integer variable that:
Keeps track of the number of events that have occurred.
Allows processes to wait until a certain event count is reached.
Instead of busy waiting continuously, a process waits for a specific event number.
1️⃣Hardware Solutions
Hardware solutions use special CPU instructions to ensure mutual exclusion.
(a) Test-and-Set Instruction (TSL)
This is an atomic instruction (executed in one step).
Working:
Checks lock value.
If lock = 0 → sets it to 1 and enters critical section.
If lock = 1 → process waits.
(b) Compare-and-Swap (CAS)
Another atomic instruction:
Compares memory value with expected value.
If equal → swaps with new value.
2️⃣Strict Alternation (Software Solution)
Strict alternation is a simple software solution for two processes.
Idea:
Two processes take turns entering the critical section.
Problems in Strict Alternation:
Violates Progress condition
If one process does not want to enter the critical section, the other must still wait.
Not efficient
So it is not a correct general solution.
3️⃣Peterson’s Solution
Developed by Gary L. Peterson.
Peterson’s solution is a software solution for two processes that satisfies:
✔ Mutual Exclusion
✔ Progress
✔ Bounded Waiting
How It Works:
Process indicates interest using flag.
Gives priority to other process using turn.
If other process is interested and it's their turn → wait.
Otherwise → enter critical section.