0% found this document useful (0 votes)
55 views

OS Unit 1 & 2 Notes

The document provides an overview of operating systems, including their functions, types, and history. It discusses the key roles of an operating system in booting a computer, managing processes, files, memory, I/O, security, and more. It outlines the evolution of operating systems from early generations that lacked them to modern batch, time-sharing, multi-programming, distributed, network, and real-time operating systems. The types of operating systems are compared in terms of their advantages and disadvantages.

Uploaded by

Sankalp
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views

OS Unit 1 & 2 Notes

The document provides an overview of operating systems, including their functions, types, and history. It discusses the key roles of an operating system in booting a computer, managing processes, files, memory, I/O, security, and more. It outlines the evolution of operating systems from early generations that lacked them to modern batch, time-sharing, multi-programming, distributed, network, and real-time operating systems. The types of operating systems are compared in terms of their advantages and disadvantages.

Uploaded by

Sankalp
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Unit 1

Fundamental Concepts of Operating System

Introduction to Operating System


An operating system is a program that acts as anintermediary between a user of a computer and the computer
hardware.
The purpose of an operating system is to provide an environment in which a user can execute programs. The
primary goal of an operating system is thus to make the computer system convenient to use.
An operating system is an important part of almost every computer system.
A computer system can be divided roughly into four components: the hardware, the operating system,the
application programs and the users (Figure 1.1).
Functions of Operating System

i. Booting the Computer


The process of starting or restarting the computer is known as booting. If the computer is switched off
completely and if turned on then it is called cold booting. Warm booting is a process of using the operating
system to restart the computer.

Steps:

1. Power ON
2. CPU will move BIOS in ROM
3. BIOS will be executed.(POST)
4. Power on self Test.

All the H/W will be tested

ii. Process Management


A process is only ONE instant of a program in execution.There are many processes can be running the
same program.

The five major activities of an operating system in regard to process


management are:
Creation and deletion of user and system processes.
Suspension and resumption of processes.
A mechanism for process synchronization.
A mechanism for process communication.

iii. File Management


A file is a collected of related information defined by its creator. Computer can store files on the disk
(secondary storage), which provide long term storage.

The creation and deletion of files.


The creation and deletion of directions.
The support of primitives for manipulating files and directions.
The mapping of files onto secondary storage.
The backup of files on stable storage media.

iv. Memory Management


The operating system manages the Primary Memory or Main Memory. Main memory is made up of a large
array of bytes or words where each byte or word is assigned a certain address. Main memory is fast storage
and it can be accessed directly by the CPU. For a program to be executed, it should be first loaded in the
main memory. An operating system manages the allocation and deallocation of the memory to various
processes and ensures that the other process does not consume the memory allocated to one process.

v. I/O System Management

One of the purposes of an operating system is to hide the peculiarities of specific hardware devices from the
user.
Secondary-Storage Management Generally speaking, systems have several levels of storage, including
primary storage, secondary storage and cache storage. Instructions and data must be placed in primarystorage
or cache to be referenced by a running program.
vi. Security and Protection
The operating system uses password protection to protect user data and similar other techniques. it also
prevents unauthorized access to programs and user data. The operating system provides various techniques
which assure the integrity and confidentiality of user data. Following security measures are used to protect
user data:
 Protection against unauthorized access through login.
 Protection against intrusion by keeping firewall active.
 Protecting the system memory against malicious access.
 Displaying messages related to system vulnerabilities.

History of Operating Systems

The 1940's - First Generations


The earliest electronic digital computers had no operating systems. Machines of the time were so primitive
that programs were often entered one bit at time on rows of mechanical switches (plug boards).
Programming languages were unknown (not even assembly languages). Operating systems were unheard of.

The 1950's - Second Generation


By the early 1950's, the routine had improved somewhat with the introduction of punch cards. The General
Motors Research Laboratories implemented the first operating systems in early 1950's for their IBM 701.
The system of the 50's generally ran one job at a time.

The 1960's - Third Generation


The systems of the 1960's were also batch processing systems, but they were able to take better advantage of
the computer's resources by runningseveral jobs at once.

Fourth Generation
With the development of LSI (Large Scale Integration) circuits, chips, operating system entered in the
personal computer and the workstation age. Microprocessor technology evolved to the point that it b+ecomes
possible to build desktop computers as powerful as the mainframes of the 1970s.

Types of Operating Systems


There are several types of Operating Systems which are mentioned below.

1. Batch Operating System


2. Time-Sharing Operating System
3. Multi-Programming System
4. Distributed Operating System
5. Network Operating System
6. Real-Time Operating System
1. Batch Operating System
This type of operating system does not interact with the computer directly. There is an operator which
takes similar jobs having the same requirement and groups them into batches. It is the responsibility of the
operator to sort jobs with similar needs.

Advantages of Batch Operating System


 It is very difficult to guess or know the time required for any job to complete. Processors of the
batch systems know how long the job would be when it is in the queue.
 Multiple users can share the batch systems.
 The idle time for the batch system is very less.
 It is easy to manage large work repeatedly in batch systems.

Disadvantages of Batch Operating System


 The computer operators should be well known with batch systems.
 Batch systems are hard to debug.
 It is sometimes costly.
 The other jobs will have to wait for an unknown time if any job fails.

2. Time-Sharing Operating Systems


Each task is given some time to execute so that all the tasks work smoothly. Each user gets the time of the
CPU as they use a single system. These systems are also known as Multitasking Systems. The task can be
from a single user or different users also. The time that each task gets to execute is called quantum. After
this time interval is over OS switches over to the next task.

Advantages of Time-Sharing OS
 Each task gets an equal opportunity.
 Fewer chances of duplication of software.
 CPU idle time can be reduced.
Disadvantages of Time-Sharing OS
 Reliability problem.
 One must have to take care of the security and integrity of user programs and data.
 Data communication problem.
 Multi-Programming Operating System

3. Multiprogramming Operating Systems


Multiprogramming Operating Systems can be simply illustrated as more than one program is present in the
main memory and any one of them can be kept in execution. This is basically used for better execution of
resources.

Advantages of Multi-Programming Operating System


 Multi Programming increases the Throughput of the System.
 It helps in reducing the response time.
Disadvantages of Multi-Programming Operating System
 There is not any facility for user interaction of system resources with the system.

4. Distributed Operating System


These types of operating system is a recent advancement in the world of computer technology and are
being widely accepted all over the world and, that too, at a great pace. Various autonomo us interconnected
computers communicate with each other using a shared communication network. Independent systems
possess their own memory unit and CPU.

Advantages of Distributed Operating System


 Failure of one will not affect the other network communication, as all systems are
independent of each other.
 Electronic mail increases the data exchange speed.
 Since resources are being shared, computation is highly fast and durable.
 Load on host computer reduces.
 These systems are easily scalable as many systems can be easily added to the network.
 Delay in data processing reduces.

Disadvantages of Distributed Operating System


 Failure of the main network will stop the entire communication.
 To establish distributed systems the language is used not well-defined yet.
 These types of systems are not readily available as they are very expensive. Not only that the
underlying software is highly complex and not understood well yet.

5. Network Operating System


These systems run on a server and provide the capability to manage data, users, groups, security,
applications, and other networking functions. These types of operating systems allow shared access to
files, printers, security, applications, and other networking functions over a small priva te network.

Advantages of Network Operating System


 Highly stable centralized servers.
 Security concerns are handled through servers.
 New technologies and hardware up-gradation are easily integrated into the system.
 Server access is possible remotely from different locations and types of systems.

Disadvantages of Network Operating System
 Servers are costly.
 User has to depend on a central location for most operations.
 Maintenance and updates are required regularly.

6. 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.
Advantages of RTOS
 Maximum Consumption: Maximum utilization of devices and systems, thus more output from all
the resources.
 Task Shifting: The time assigned for shifting tasks in these systems is very less. For example, in
older systems, it takes about 10 microseconds in shifting from one task to another, and in the latest
systems, it takes 3 microseconds.
 Focus on Application: Focus on running applications and less importance on applications that are
in the queue.
 Real-time operating system in the embedded system: Since the size of programs is small, RTOS
can also be used in embedded systems like in transport and others.
 Error Free: These types of systems are error-free.
 Memory Allocation: Memory allocation is best managed in these types of systems.

Disadvantages of RTOS
 Limited Tasks: Very few tasks run at the same time and their concentration is very less on a few
applications to avoid errors.
 Use heavy system resources: Sometimes the system resources are not so good and they are
expensive as well.
 Complex Algorithms: The algorithms are very complex and difficult for the designer to write on.

Operating Systems Services


Program Execution
The system must be able to load a program into memory and to run it. The program must be able to end its
execution, either normally or abnormally (indicating error).
I/O Operations
A running program may require I/O. This I/O may involve a file or an I/O device.
File System Manipulation
The output of a program may need to be written into new files or input taken from some files. The operating
system provides this service.
Error Detection
An error is one part of the system may cause malfunctioning of the complete system. To avoid such a situation
the operating system constantly monitors the system for detecting the errors.
Communication
The OS handles routing and connection strategies, and the problems of contention and security. Following
are the major activities of an operating system with respect to communication –
Two processes often require data to be transferred between them
Both the processes can be on one computer or on different computers, but are connected through a computer
network. Communication may be implemented by two methods, either by Shared Memory or by Message
Passing.

System Calls and System Programs


• The interface between a process and an operating system is provided by system calls
• System calls are usually made when a process in user mode requires access to a resource. Then it
requests the kernel to provide the resource via a system call.

Types of system call

• Process Control
These system calls deal with processes such as process creation, process termination etc.

• File Management
These system calls are responsible for file manipulation such as creating a file, reading a file, writing
into a file etc.

• Device Management
These system calls are responsible for device manipulation such as reading from device buffers,
writing into device buffers etc.

• Information Maintenance
These system calls handle information and its transfer between the operating system and the user
program.

• Communication
These system calls are useful for interprocess communication. They also deal with creating and
deleting a communication connection.
Types Of System Calls

Types of System Calls Windows Linux

Process Control CreateProcess() fork()


ExitProcess() exit()
WaitForSingleObject() wait()

File Management CreateFile() open()


ReadFile() read()
WriteFile() write()
CloseHandle() close()

Device Management SetConsoleMode() ioctl()


ReadConsole() read()
WriteConsole() write()

Information GetCurrentProcessID() getpid()


Maintenance SetTimer() alarm()
Sleep() sleep()

Communication CreatePipe() pipe()


CreateFileMapping() shmget()
MapViewOfFile() mmap()

wait()
In some systems, a process may wait for another process to complete its execution. This happens
when a parent process creates a child process and the execution of the parent process is suspended
until the child process executes. The suspending of the parent process occurs with a wait() system
call. When the child process completes execution, the control is returned back to the parent process.

exec()
This system call runs an executable file in the context of an already running process. It replaces the
previous executable file. This is known as an overlay. The original process identifier remains sinc e
a new process is not created but data, heap, stack etc. of the process are replaced by the new
process.

• fork()
Processes use the fork() system call to create processes that are a copy of themselves. This is one of
the major methods of process creation in operating systems. When a parent process creates a child
process and the execution of the parent process is suspended until the child process executes. When
the child process completes execution, the control is returned back to the parent process.

• exit()
The exit() system call is used by a program to terminate its execution. In a multithreaded
environment, this means that the thread execution is complete. The operating system reclaims
resources that were used by the process after the exit() system call.

• kill()
The kill() system call is used by the operating system to send a termination signal to a process that
urges the process to exit. However, kill system call does not necessary mean killing the process and
can have various meanings.

Shell script

A shell script is a computer program designed to be run by the Unix/Linux shell which could be one of the
following:

 The Bourne Shell


 The C Shell
 The Korn Shell
 The GNU Bourne-Again Shell

A shell is a command-line interpreter and typical operations performed by shell scripts include file
manipulation, program execution, and printing text.

Shell Scripts

The basic concept of a shell script is a list of commands, which are listed in the order of execution. A good
shell script will have comments, preceded by # sign, describing the steps.
There are conditional tests, such as value A is greater than value B, loops allowing us to go through massive
amounts of data, files to read and store data, and variables to read and store data, and the script may include
functions.
Shell scripts and functions are both interpreted. This means they are not compiled.
Shell commands
1. In
By using this command a hard link(actual file on Linux) is created to existing file
2. wc
Command for word count. With this we can find no of lines, word count, byte & characters
count in the files
3. unmask
newly created file permissions are restricted by using “mask” The unmask cmd is used to set this
mask.
Grep: globle regular expression print
grep displays the entire line which has the matched string.
4. cut
it cuts out the sections from each line of files and writes the result to standard output

 Echo command: The echo command is used for printing.

 Using a variable: A variable is used to store in some value so that the whole value does not need to

be repeated and instead variables can be used.

 Cat: This Shell Scripting command is used to show the file contents. It is one of the very important

commands used in Linux.

 Grep: Another very important command which is used to search for a particular text within the file

and generate the output for you related to the pattern being matched.

 Greater than symbol (>): This is used if you want to save the text written on the console to be saved

into the file.


 Ls: As the name suggests, ls is the command which is responsible for listing the folders and files

present in a particular directory. This shell scripting command is often appended with other

commands such as –ltr or –lrt, etc. depending upon the need.

 Piping ( | ): This is another very basic command of Linux based operating system that is used to fetch

the output received from one command straight away into another. This symbol called pipe can most

often be seen along with the grepping command. At some places, this piping can also be said to be

chaining.

 Lesser than symbol (<): If you wish to take the input from files directly then < symbol will be used.
 Pwd: This is another very basic Linux command which is used to tell the present working directory

and hence the name pwd. It is most essential when you need to know which subfolder you are in, of a

folder.

 Mkdir and cd: These two commands go hand in hand. Mkdir, on one hand, is responsible to create

or make a directory, on the other hand, a cd is used to change a directory by traversing in it. These

commands only work for directory/folders and not on files.

Uses of shell scripting

Used by System Administrator


System administrator uses shell scripting to automate the repetitive tasks, account creation for different users,

monitoring the system status, usage of memory, running process on a system, kill or terminate multiple

processes, can interact directly with operating system and made changes at system level so that it will reflect

after the system reboot, can develop scripts to perform during the boot operation of the system.

Data Backup
Shell scripts can be used to automate the data backup process by creating a Korn job and schedule the shell

script to execute data backup commands and perform the task in an easy way along with the timestamp will

be stored so it will be easy to use them later when we want to use the backup of a particular day, data
archiving, restoring the system to a particular date can be done by using shell scripts, we can monitor the

system status while doing backup operation, restore operation. We can do the system restore by using the

backup data which we stored previously by using shell scripts we can achieve all the operations.

3. Programming
Shell scripts can be used by programmers to develop programs, scripts to perform system-level tasks, finding

patterns in a file, processing the data in a file based on the user inputs, etc. can be done using shell scripts.

Shell scripts can be used like other programming languages as we have built-in functions such as for loop,

while loop, until loop, etc.

4. Automation
Shell scripting can be used to automate several daily tasks, repetitive tasks, etc. If we want to execute the

same command multiple times then we can use shell script built-in functions like for loop, while loop etc. If

we want to find a pattern in a file we can use sed/awk and the same thing we can apply when we want to find

patterns in multiple files.


Unit 2
Process Management
The operating system is responsible for the following activities inconnection with process management: the
creation and deletion of both user and system processes; the scheduling of processes; and the provision of
mechanisms for synchronization, communication, and deadlock handling for processes.

Operations on Processes
System must provide mechanisms for:
● Process creation,
● Process termination,

Process Creation
Parent process create children processes, which, in turn create other processes, forming a tree of processes
● Generally, process identified and managed via a process identifier (pid)
● Resource sharing options
● Parent and children share all resources
● Children share subset of parent’s resources
● Parent and child share no resources
● Execution options
● Parent and children execute concurrently
● Parent waits until children terminate

Process Termination
Some operating systems do not allow child to exists if its parent has terminated. If a process terminates, then
all its children must also be terminated.
● cascading termination. All children, grandchildren, etc. are terminated.
● The termination is initiated by the operating system.
● The parent process may wait for termination of a child process by using the wait()system call.

Process State
As a process executes, it changes state. The state of a process is defined in part by the current activity of that
process. Each process may be in one of the following states:

New State: The process being created.


Running State: A process is said to be running if it has the CPU, that is, process actually using the CPU at
that particular instant.
Blocked (or waiting) State: A process is said to be blocked if it is waiting for some event to happen such that as
an I/O completion before it can proceed. Note that a process is unable to run until some external event
happens.
Ready State: A process is said to be ready if it is waiting to be assigned to aprocessor.
Terminated state: The process has finished execution.
Fig: process states

Process Control Block


Each process is represented in the operating system by aprocess control block PCS)—also called a task
control block.

Process state

process number

program counter
Registers

memory limits

list of open files

.
.

Figure : Process control block.

The following are the data items −

Process State
This specifies the process state i.e. new, ready, running, waiting or terminated.

Process Number
This shows the number of the particular process.
Program Counter
This contains the address of the next instruction that needs to be executed in the process.

Registers
This specifies the registers that are used by the process. They may include accumulators, index registers, stack
pointers, general purpose registers etc.

List of Open Files


These are the different files that are associated with the process

CPU Scheduling Information


The process priority, pointers to scheduling queues etc. is the CPU scheduling information that is contained in
the PCB. This may also include any other scheduling parameters.

Memory Management Information


The memory management information includes the page tables or the segment tables depending on the memory
system used. It also contains the value of the base registers, limit registers etc.

I/O Status Information


This information includes the list of I/O devices used by the process, the list of files etc.

Accounting information
The time limits, account numbers, amount of CPU used, process numbers etc. are all a part of the PCB
accounting information.

Schedulers

 Short-term scheduler (or CPU scheduler) – selects which process should be executed next and
allocates CPU
Sometimes the only scheduler in a system
Short-term scheduler is invoked frequently (milliseconds) ⇒ (must be fast)

● Long-term scheduler (or job scheduler) – selects which processes should be brought into the ready queue
Long-term scheduler is invoked infrequently (seconds, minutes) ⇒ (may be slow)
The long-term scheduler controls the degree of multiprogramming

● Processes can be described as either:


I/O-bound process – spends more time doing I/O than computations, many short CPU bursts. CPU-bound
process – spends more time doing computations; few very long CPU bursts.

● Long-term scheduler strives for good process mix


Types of Scheduling

1. Preemptive
2. Non Preemptive Scheduling

1. Preemptive Scheduling

Preemptive Scheduling is a CPU scheduling technique that works by dividing time slots of CPU to
a given process.
The time slot given might be able to complete the whole process or might not be able to it.
When the burst time of the process is greater than CPU cycle, it is placed back into the ready queue
and will execute in the next chance. This scheduling is used when the process switch to ready state.
Algorithms that are backed by preemptive Scheduling are round-robin (RR), priority, SRTF
(shortest remaining time first)(also called as SJF Preemtive)

2. Non Preemptive Scheduling

Non-preemptive Scheduling is a CPU scheduling technique the process takes the resource (CPU
time) and holds it till the process gets terminated or is pushed to the waiting state.
No process is interrupted until it is completed, and after that processor switches to another process.
Algorithms that are based on non-preemptive Scheduling are non-preemptive priority, and shortest
Job first.

CPU Scheduling
CPU scheduling is the basis of multiprogramming operatingsystems. By switching the CPU among
processes, the operatingsystem can make the computer more productive.

Scheduling Criteria

Different CPU scheduling algorithms have different properties and may favor one class of processes over
another. In choosing which algorithm to use in a particular situation, we must consider the properties of the
various algorithm.

Many criteria have been suggested for comparing CPUscheduling algorithms.

Criteria that are used include the following:


CPU utilization.
Throughput.
Turnaround time.
Waiting time.
Response time.

Scheduling Algorithms

1. First-Come, First-Served Scheduling

2. Shortest-Job-First Scheduling
3. Priority Scheduling

4. Round-Robin Scheduling

1. First-Come, First-Served Scheduling


Given n processes with their burst times, the task is to find average waiting time and average turn around
time using FCFS scheduling algorithm.
First in, first out (FIFO), also known as first come, first served (FCFS), is the simplest scheduling
algorithm. FIFO simply queues processes in the order that they arrive in the ready queue.
In this, the process that comes first will be executed first and next process starts only after the previous
gets fully executed.
Here we are considering that arrival time for all processes is 0.
How to compute below times in Round Robin using a program?
Completion Time: Time at which process completes its execution.
Turn Around Time: Time Difference between completion time and arrival time. Turn Around Time =
Completion Time – Arrival Time
Waiting Time(W.T): Time Difference between turn around time and burst time.
Waiting Time = Turn Around Time – Burst Time

Process Burst Time

P1 24

P2 3

P3 3

P1 P2 P3
0 24 27 30

2. Shortest-Job-First Scheduling
The shortest job first (SJF) or shortest job next, is a scheduling policy that selects the waiting process wi th
the smallest execution time to execute next. SJN, also known as Shortest Job Next (SJN).
Algorithm:
Sort all the processes according to the arrival time.
Then select that process that has minimum arrival time and minimum Burst time.
After completion of the process make a pool of processes that arrives afterward till the completion of the
previous process and select that process among the pool which is having minimum Burst time.

Process Burst Time


P1 6

P2 8

P3 7

P4 3

P4 P1 P3 P2
0 3 9 16 24
3. Priority Scheduling
Priority scheduling is a non-preemptive algorithm and one of the most common scheduling algorithms in
batch systems. Each process is assigned first arrival time (less arrival time process first) if two processes
have same arrival time, then compare to priorities (highest process first). Also, if two processes have same
priority then compare to process number (less process number first). This process is repeated while all
process get executed.
Implementation –
First input the processes with their arrival time, burst time and priority.
First process will schedule, which have the lowest arrival time, if two or more processes will have lowest
arrival time, then whoever has higher priority will schedule first.
Now further processes will be schedule according to the arrival time and priority of the process. (Here we
are assuming that lower the priority number having higher priority). If two process priority are same then
sort according to process number.
Note: In the question, They will clearly mention, which number will have higher priority and which
number will have lower priority.
Once all the processes have been arrived, we can schedule them based on their priority.

Process Burst Time Priority

P1 10 3
P2 1 1
P3 2 3
P4 1 4
P5 5 2

P2 P5 P1 P3 P4
4. Round-Robin Scheduling
A round-robin scheduling algorithm is used to schedule the process fairly for each job a time slot or
quantum and the interrupting the job if it is not completed by then the job come after the other job which is
arrived in the quantum time that makes these scheduling fairly.

Inter Process Communication (IPC)


A process can be of two types:
 Independent process.
 Co-operating process.
An independent process is not affected by the execution of other processes while a co-operating process
can be affected by other executing processes. Though one can think that those processes, which are
running independently, will execute very efficiently, in reality, there are many situations when co-
operative nature can be utilized for increasing computational speed, convenience, and modularity. Inter -
process communication (IPC) is a mechanism that allows processes to communicate with each other and
synchronize their actions. The communication between these processes can be seen as a method of co -
operation between them. Processes can communicate with each other through both:

1. Shared Memory
2. Message passing
Figure 1 below shows a basic structure of communication between processes via the shared memory
method and via the message passing method.

An operating system can implement both methods of communication. First, we will discuss the shared
memory methods of communication and then message passing. Communication between processes using
shared memory requires processes to share some variable, and it completely depends on how the
programmer will implement it. One way of communication using shared memory can be imagined like
this: Suppose process1 and process2 are executing simultaneously, and they share some resources or use
some information from another process. Process1 generates information about certain computations or
resources being used and keeps it as a record in shared memory. When process2 needs to use the shared
information, it will check in the record stored in shared memory and take note of the information generated
by process1 and act accordingly. 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.
Let’s discuss an example of communication between processes using the shared memory method.

Shared Memory Method


Ex: Producer-Consumer problem
There are two processes: Producer and Consumer. The producer produces some items and the Consumer
consumes that item. The two processes share a common space or memory location known as a buffer
where the item produced by the Producer is stored and from which the Consumer consumes the item if
needed. There are two versions of this problem: the first one is known as the unbounded buffer problem in
which the Producer can keep on producing items and there is no limit on the size of the buffer, the second
one is known as the bounded buffer problem in which the Producer can produce up to a certain number of
items before it starts waiting for Consumer to consume it. We will discuss the bounded buffer problem.
First, the Producer and the Consumer will share some common memory, then the producer will start
producing items. If the total produced item is equal to the size of the buffer, the producer will wait to get it
consumed by the Consumer. Similarly, the consumer will first check for the availability of the item. If no
item is available, the Consumer will wait for the Producer to produce it. If there are items available,
Consumer will consume them. The pseudo-code to demonstrate is provided below:
Shared Data between the two Processes

Thread in Operating System

What is a Thread?

A thread is a path of execution within a process. A process can contain multiple threads.

A thread is also known as lightweight process.


The idea is to achieve parallelism by dividing a process into multiple threads.
For example, in a browser, multiple tabs can be different threads. MS Word uses multiple threads: one
thread to format the text, another thread to process inputs, etc.

Process vs 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 process, a thread has its own program counter (PC), register set, and stack space.
Advantages of Thread over Process

1. Responsiveness:

If the process is divided into multiple threads, if one thread completes its execution, then its output can be
immediately returned.

2. Faster context switch:

Context switch time between threads is lower compared to process context switch. Process context
switching requires more overhead from the CPU.

3. Effective utilization of multiprocessor system:

if we have multiple threads in a single process, then we can schedule multiple threads on multiple
processor. This will make process execution faster.

4. Resource sharing:

Resources like code, data, and files can be shared among all threads within a process.
Note: stack and registers can’t be shared among the threads. Each thread has its own stack and registers.

5. Communication:

Communication between multiple threads is easier, as the threads shares common address space. while in
process we have to follow some specific communication technique for communication between two
process.

Types of Threads
There are two types of threads.
User Level Thread
Kernel Level Thread

1. User Threads

 These threads are implemented and used in the user library. They cannot be created using the system.
 While doing thread switching, if the OS is called there will be distractions.

 The user thread avoids all distractions and does not interrupt the kernel system.

 These threads are considered as single-threaded processes by the kernel.

 These are implemented on the systems that do not support multithreading as it is a single thread
process. These are simply represented with a single, register, counter and stack.

 The user threads do not create any separate tasks for creation. The switching is also fast as there is no
OS intervention.

 There is no coordination between threads and kernel and hence if one thread breaks, the entire
process is blocked.

2. Kernel Threads

 Kernel manages the threads and knows each and every thread. This is a multithreading type.
 The kernel manages a table to track the threads in each process. Also, there is a separate table to
track the processes and update whenever the changes are made.
 OS makes the changes in the thread while creating and managing them. Knowledge of threads is
shared with the kernel and hence the time for each process is scheduled according to the execution.
 Kernel threads are used for applications that break in between the process.
 Kernel threads are slow when compared with user threads. The thread control block is needed to
control the tasks.

In a specific implementation, the user threads must be mapped to kernel threads, using one of the following
strategies.

Many-To-One Model

 In the many-to-one model, many user-level threads are all mapped onto a single kernel thread.
 Thread management is handled by the thread library in user space, which is very efficient.
 However, if a blocking system call is made, then the entire process blocks, even if the other user
threads would otherwise be able to continue.
 Because a single kernel thread can operate only on a single CPU, the many-to-one model does not
allow individual processes to be split across multiple CPUs.
 Green threads for Solaris and GNU Portable Threads implement the many-to-one model in the past,
but few systems continue to do so today.
One-To-One Model

 The one-to-one model creates a separate kernel thread to handle each user thread.
 One-to-one model overcomes the problems listed above involving blocking system calls and the
splitting of processes across multiple CPUs.
 However the overhead of managing the one-to-one model is more significant, involving more
overhead and slowing down the system.
 Most implementations of this model place a limit on how many threads can be created.
 Linux and Windows from 95 to XP implement the one-to-one model for threads.

Many-To-Many Model

 The many-to-many model multiplexes any number of user threads onto an equal or smaller number
of kernel threads, combining the best features of the one-to-one and many-to-one models.
 Users have no restrictions on the number of threads created.
 Blocking kernel system calls do not block the entire process.
 Processes can be split across multiple processors.
 Individual processes may be allocated variable numbers of kernel threads, depending on the
number of CPUs present and other factors.

Threading Issues
Some of the issues related to thread are
1. The Fork () and EXEC() system Call
2. Thread Cancellation
3. Signal Handling
4. Thread Pool

1. The Fork () and EXEC() system Call


Fork()—new process is created which is duplicate copy of parent process
Let p1 process calls fork ()system call then p2 process is created
Here p2 is exact duplicate of its parent process P1
Exec() used in order to replace the process with new process

You might also like