Unit-3 Os CSBS

Download as pdf or txt
Download as pdf or txt
You are on page 1of 139

Noida Institute of Engineering and Technology, Greater Noida

Inter-Process Communication and Deadlock

Unit: 3

Operating System (ACSBS0403)


Rifa Nizam Khan
Assistant Professor
Course Details CSBS
(B Tech CSBS 4th Sem )

Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3


1
3/13/2024
Faculty Introduction

Work Experience
Education Publications
• NIET, Gr Noida From Nov 2021 to till date
• GNIOT, Gr Noida From Oct 2019 to Nov 2021 • M.Tech (AKTU, Lucknow) Total: 04
• TIAS, Delhi From Jan 2019 to July 2019 • B.Tech (AKTU, Lucknow) International: 2 (DRDO, Delhi)
• SRMSCET, Bareilly From Jan 2017 to Nov 2017
• PHD (pursuing Jamia Millia National: 2
Islamia, Delhi)

➢ Awarded by Scholarship In M.Tech.


➢ Give Guest Lecture on Cloud Computing In Company Training Basket Pvt Ltd, Noida
➢ Attended 11 FDPs , Coordinated International Conference, NATCOM at SRMSCET campus.
3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 2
Evaluation Scheme

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 3


Course Contents / Syllabus

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 4


Course Contents / Syllabus

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 5


Course Contents / Syllabus

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 6


Textbooks and References

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 7


Branch wise Applications
• Operating System is a software that is going to use in every computer based technology whether it
is Computer System, Embedded System or any other computing device
• Operating System provides an environment to the user so that they can interact with the hardware
of a machine like Computer System. It allows user to install different Application Software, so
that user can perform some specific task
• In today, Digital World space is more important to store data for future use and Operating System
also manage the memory of system, it also creates virtual memory that creates an illusion for user
of more memory.
• Some more tasks like Device Management, Process Management and File Management are
performed by Operating System.
• Operating System like UNIX also provide opportunities to programmers to trouble shoot the
network problem.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 8


Course Objective
• The course objective is to enable students to understand the concept of Operating System and
it’s importance in computer system.
• To Design an Operating System that could work efficiently in comparison of existing
Operating Systems by implementing different types of CPU scheduling algorithms.
• To manage the Memory available in OS to store more data by using the concept of virtual
memory and Memory Management
• To understand the process of communication between different processes and solve the
problem of deadlock that arises because of resource sharing the same time
• To understand the concept of File and Disk Management, so that more space can be available
for storing data.
• To understand the concept of shell programming in UNIX OS

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 9


Course Outcomes

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 10


Program Outcome

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and
an engineering specialization for the solution of complex engineering problems.
2. Problem analysis: Identify, formulate, research literature, and analyze complex engineering problems
reaching substantiated conclusions using first principles of mathematics, natural sciences, and engineering
sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for public
health and safety, and cultural, societal, and environmental considerations.
4. Conduct investigations of complex problems: Use research based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of information to provide
valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering
and IT tools, including prediction and modeling to complex engineering activities, with an understanding of
the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 11
Program Outcome

17. Environment and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the engineering
community and with the society at large, such as, being able to comprehend and write effective reports and
design documentation, make effective presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one’s own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 12


CO-PO Mapping

OPERATING SYSTEM(ACSBS-403)
CODE PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12

CO1 3 3 2 2 1 2 - 2 3 2 2 3
CO2 3 3 3 2 2 3 2 2 3 - 1 3
CO3 3 3 2 2 2 2 2 2 2 3 1 3
CO4 3 2 2 3 1 2 2 - 2 - 2 3
CO5 3 1 2 2 2 2 - - 2 2 2 3

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 13


Program Specific Outcomes (PSOs)

At the end of the program, the student will be able to

PSO1: Apply technical and business knowledge to solve complex problems and face
current business challenges.

PSO2: Explore modern tools and technologies and apply the knowledge to design and
develop solutions for betterment of the society.

PSO3: Work innovatively and communicate effectively with professionals worldwide


and pursue lifelong learning to add value to society and environment.

Ms. Rifa Nizam Khan ACSBS0403 Operating


3/13/2024 14
System Unit 3
CO- PSO Mapping

Program Specific Outcomes


Course
Outcomes
PSO1 PSO2 PSO3 PSO4

CO1 2 1 2 2

CO2 2 2 1 2

CO3 2 3 3 2

CO4 2 2 1 2

CO5 2 2 2 2

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 15


Program Educational Objectives(PEOs)
The graduates of B.Tech Data CSBS program will

PEO1: Engage in successful professional practices in emerging areas of computer science and
business systems and pursue higher education and research.

PEO2: Adapt easily to dynamically changing environment, applying their knowledge in technology
abstraction and common business principles.

PEO3: Demonstrate effective business communication with innovation mindset who can effectively
work in a team and exhibit strong ethics and life values to serve the society.

Ms. Rifa Nizam Khan ACSBS0403 Operating


3/13/2024 16
System Unit 3
Result Analysis

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 17


End Semester Question Paper Template

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 18


Prerequisite and Recap

• Basic knowledge of computer fundamentals.

• Basic knowledge of computer organization.

• Memory hierarchy

• Cache Organization

• Interrupt

• Registers

• Associative memory

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 19


Brief Introduction about the Subject

For Computer Engineers/Students, it important that they must be aware about the Operating System and
its task because operating system is the first things that is required to communicated with hardware of
computer system like mouse, monitor, mother board, printer, etc. Operating System provides an
environment to users where they can install many more application software to perform their specific
tasks. In short Operating System acts as an interface between Users and Hardware of Computer System.
Operating System also perform the task of Memory Management, Processor Management, Device
Management, File Management, Security Control over system performance, Job accounting, Error
detecting aids and Coordination between other software and users. Some popular Operating Systems
include Linux Operating System, Windows Operating System, VMS, OS/400, AIX, z/OS, etc.
This subject helps students to know about the Operating System in detail and understand the management
of different resources like memory, disk management, process scheduling etc.

https://www.youtube.com/watch?v=mXw9ruZaxzQ
https://www.youtube.com/watch?v=vBURTt97EkA

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 20


Unit-3 Content

• Concurrent processes,
• precedence graphs,
• Critical Section,
• Race Conditions,
• Mutual Exclusion,
• Hardware Solution,
• Semaphores,
• Strict Alternation, Peterson’s Solution,
• The Producer / Consumer Problem,
• Peterson’s solution,
• Lamport Bakery solution,
• Semaphores,
• Test and Set operation Event Counters, Monitors, Message Passing,

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 21


Unit-3 Content
• Classical IPC Problems:
• Reader’s & Writer Problem,
• Dinning Philosopher Problem,
• Barber’s shop problem,
• Inter Process Communication models and Schemes,
• Process generation.
• Definition, Necessary and sufficient conditions for Deadlock,
• Deadlock Prevention,
• Deadlock Avoidance: Banker’s algorithm,
• Deadlock detection and Recovery.
• Concurrent Programming: Critical region, conditional Critical region,
Monitors,
• Concurrent languages,
• Communicating Sequential Process (CSP);

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 22


Unit Objective

After going through this unit, you should be able to:


▪ Understand the concept Process communication
▪ Able to understand Critical region and race conditions
▪ Understand the concept of Semaphore
▪ Understand different algorithms to solve critical section problem and race condition
problem
▪ Understand the concept of Deadlock and solution of deadlock conditions

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 23


Topic Objective

After going through this lecture, you should be able to:


▪ To understand the concept of IPC and Precedence Graph
▪ To know about Critical Section and Race condition
▪ Understand the concept of Semaphore and its types
▪ Understand different algorithms to solve critical section problem and race condition
problem
▪ Understand the concept of Deadlock and solution of deadlock conditions

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 24


Introduction of IPC
• Inter-process communication is the mechanism provided by the operating system that allows processes
to communicate with each other.
• This communication could involve a process letting another process know that some event has occurred
or the transferring of data from one process to another.
• Synchronization in Interprocess Communication
Synchronization is a necessary part of interprocess communication. It is either provided by the
interprocess control mechanism or handled by the communicating processes. Some of the methods to
provide synchronization are as follows −
• Semaphore A semaphore is a variable that controls the access to a common resource by multiple
processes. The two types of semaphores are binary semaphores and counting semaphores.
• Mutual Exclusion: Mutual exclusion requires that only one process thread can enter the critical section
at a time. This is useful for synchronization and also prevents race conditions.
• Barrier: A barrier does not allow individual processes to proceed until all the processes reach it. Many
parallel languages and collective routines impose barriers.
• Spinlock: This is a type of lock. The processes trying to acquire this lock wait in a loop while checking
if the lock is available or not. This is known as busy waiting because the process is not doing any useful
operation even though it is active.
3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 25
Concurrent Processing
• Concurrent processing is a computing model in which multiple processors execute instructions
simultaneously for better performance.
• Concurrent means, which occurs when something else happens.
• The tasks are broken into sub-types, which are then assigned to different processors to perform
simultaneously, sequentially instead, as they would have to be performed by one processor.
• Concurrent processing is sometimes synonymous with parallel processing.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 26


Concurrent Process
• Multiprogramming Environment :
In multiprogramming environment, there are multiple tasks shared by one processor. while a
virtual concert can be achieved by the operating system, if the processor is allocated for each
individual task, so that the virtual concept is visible if each task has a dedicated processor. The
multilayer environment shown in figure.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 27


Concurrent Process
• Multiprocessing Environment :
In multiprocessing environment two or more processors are used with shared memory. Only one
virtual address space is used, which is common for all processors. All tasks reside in shared
memory. In this environment, concurrency is supported in the form of concurrently executing
processors. The tasks executed on different processors are performed with each other through
shared memory. The multiprocessing environment is shown in figure.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 28


Concurrent Process
• Distributed Processing Environment :
In a distributed processing environment, two or more computers are connected to each other by a
communication network or high speed bus. There is no shared memory between the processors
and each computer has its own local memory. Hence a distributed application consisting of
concurrent tasks, which are distributed over network communication via messages. The
distributed processing environment is shown in figure.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 29


Precedence Graph
• Precedence Graph is a directed acyclic graph which is used to show the execution level of
several processes in operating system.
• It consists of nodes and edges.
• Nodes represent the processes, and the edges represent the flow of execution.
Properties of Precedence Graph :
• It is a directed graph.
• It is an acyclic graph.
• Nodes of graph correspond to individual statements of program code.
• Edge between two nodes represents the execution order.
• A directed edge from node A to node B shows that statement A executes first and then Statement
B executes.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 30


Precedence Graph

If above code is executed concurrently, the following


precedence relations exist:
•c = a – b cannot be executed before both a and b have
been assigned values.
•w = c + 1 cannot be executed before the new values of c
has been computed.
•The statements a = x + y and b = z + 1 could be executed
concurrently.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 31


Precedence Graph

Consider the following precedence relations of a program:


1.S2 and S3 can be executed after S1 completes.
2.S4 can be executed after S2 completes.
3.S5 and S6 can be executed after S4 completes.
4.S7 can be executed after S5, S6 and S3 complete.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 32


Critical Section

• A critical section is a code segment that accesses shared variables and has to be executed as an
atomic action.
• It means that in a group of co-operating processes, at a given point of time, only one process
must be executing its critical section.
• If other processes also want to execute its critical section, it must wait until the first one
finishes.
• Critical section: It is the part of the program where shared resources are accessed by various
processes.
• It is the place where shared variable, resources are placed.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 33


Precedence Graph

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 34


Solution to Critical section Problem

• A solution to the critical section problems must satisfy the following three conditions:
1. Mutual exclusion
2. Progress
3. Bounded waiting
4. No assumption related to H/W speed

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 35


Solution to Critical section Problem

1. Mutual exclusion Out of a group of co-operating processes, only one process can be in its
critical section at a given point of time.
2. Progress: If no process is in its critical section and if one or more process wants to execute in
critical section than one of these process must be allowed to get into its critical section.
3. Bounded waiting: After a process makes a request for getting into its critical section, there is
a limit for how many other processes can get into their critical section, before this process’s
request is granted. So after the limit time is reached, system must grant the process permission
to get into its critical section.
4. No assumption related to H/W speed

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 36


Race Conditions

1. A race condition is a condition when there are many processes and every process shares the
data with each other and accessing the data concurrently, and the output of execution depends
on a particular sequence in which they share the data and access.
2. To prevent the race condition, we need to ensure that only one process can access the shared
data at a time. This is the main reason why we need to synchronize the processes. we can
describe the race condition as follows;

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 37


Race Conditions

Here we have used two variables. Suppose variable is a shared


variable. Now let’s say that bankAccount function is called for Void bankAccount(double money)
its execution. The statements of this function will be executed
in the following sequence; {
•The previous value of the shared variable will be loaded
shared= shared + money
into one of the registers of the CPU.
•The value of money variable will be loaded into some }
another register.
•The values of two variables will be stored in two registers
and the result will be calculated.
•Now, assign the result to the variable share.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 38


Race Conditions

• For example, there are two processes P1 and P2 and both P1 and P2 processes are willing to
call the function bankAccount concurrently.
• suppose P1 call the function of bank account by passing the parameters of the function and the
value of the parameter is 200 and similarly, P2 call the function of the bankAccount by passing
the value of the parameter as 100.
• Now, let’s suppose that the previous value of the shared variable is 1100. in this example we
are resuming that process P1 and P2 are executed on the different processors.
•.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 39


Race Conditions

The result can be looks like;


•Process P1 loads 1100 into the CPU register
•P2 will load 1100 into its register.
•P1 will add 200 to its register then the result will be 1300
•The process P2 will add 100 its register and the calculated result will be 1200
•The process P1 will store 1400 in shared variable and the process P2 will store 1150 in a
shared variable.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 40


Mutual Exclusion

Mutual exclusion Out of a group of co-operating processes, only one process can be in its critical
section at a given point of time.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 41


Hardware Solution

• When two or more process cooperates with each other, their order of execution must be
preserved otherwise there can be conflicts in their execution and inappropriate outputs can be
produced.

• A cooperative process is the one which can affect the execution of other process or can be
affected by the execution of other process. Such processes need to be synchronized so that their
order of execution can be guaranteed.

• The procedure involved in preserving the appropriate order of execution of cooperative


processes is known as Process Synchronization. There are various synchronization
mechanisms that are used to synchronize the processes.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 42


Semaphore

Semaphore was proposed by Dijkstra in 1965 which is a very significant technique to manage
concurrent processes by using a simple integer value, which is known as a semaphore.
Semaphore is simply an integer variable that is shared between threads.
This variable is used to solve the critical section problem and to achieve process synchronization
in the multiprocessing environment.
Semaphores are of two types:
Binary Semaphore –
• This is also known as mutex lock.
• It can have only two values – 0 and 1.
• Its value is initialized to 1.
• It is used to implement the solution of critical section problems with multiple processes.
Counting Semaphore –
• Its value can range over an unrestricted domain.
• It is used to control access to a resource that has multiple instances.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 43


Semaphore

Some point regarding P and V operation :


1.P operation is also called wait, sleep, or down
operation, and V operation is also called signal,
wake-up, or up operation.
2.Both operations are atomic and semaphore(s) is
always initialized to one. Here atomic means that
variable on which read, modify and update
happens at the same time/moment with no pre-
emption i.e. in-between read, modify and update
no other operation is performed that may change
the variable.
3.A critical section is surrounded by both
operations to implement process synchronization.
See the below image. The critical section of
Process P is in between P and V operation.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 44


Semaphore

Advantages of semaphore
• The mutual exclusion principle is followed when you use semaphores because semaphores
allow only one process to enter into the critical section.
• Here, you need not verify that a process should be allowed to enter into the critical section
or not. So, processor time is not wasted here.
Disadvantages of semaphore
• While using semaphore, if a low priority process is in the critical section, then no other
higher priority process can get into the critical section. So, the higher priority process has
to wait for the complete execution of the lower priority process.
• The wait() and signal() functions need to be implemented in the correct order. So, the
implementation of a semaphore is quite difficult.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 45


Peterson’s Solution

• A classic software-based solution to the critical-section problem known as Peterson’s solution.


• Does not require strict alternation.
• Peterson’s solution is restricted to two processes that alternate execution between their CSs and
remainder sections. The processes are numbered P0 and P1.
• Peterson’s solution requires two data items to be shared between the two processes:
int turn; boolean flag[2];
– The variable turn indicates whose turn it is to enter its CS. That is, if turn == i, then process Pi is
allowed to execute in its CS.
– The flag array is used to indicate if a process is ready to enter its CS. For example, if flag[i] is true
this value indicates that Pi is ready to enter its CS.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 46


Peterson’s Solution: Algorithm

• To enter the CS, process Pi first sets flag[i] to


be true and then sets turn to the value j,
thereby asserting that if the other process
wishes to enter the CS, it can do so.
• If both processes try to enter at the same time,
turn will be set to both i and j at roughly the
same time. Only one of these assignments will
last; the other will occur but will be
overwritten immediately.
• The eventual value of turn decides which of
the two processes is allowed to enter its CS
first.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 47


Peterson’s Solution: Algorithm

• To enter the CS, process Pi first sets flag[i] to


be true and then sets turn to the value j,
thereby asserting that if the other process
wishes to enter the CS, it can do so.
• If both processes try to enter at the same time,
turn will be set to both i and j at roughly the
same time. Only one of these assignments will
last; the other will occur but will be
overwritten immediately.
• The eventual value of turn decides which of
the two processes is allowed to enter its CS
first.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 48


The Producer / Consumer Problem

• The Producer-Consumer problem is used for multi-process synchronization i.e. synchronization


between more than one processes.
• In the producer-consumer problem, there is one Producer that is producing something and there
is one Consumer that is consuming the products produced by the Producer.
• The producers and consumers share the same memory buffer that is of fixed-size.
• The job of the Producer is to generate the data, put it into the buffer, and again start generating
data.
• While the job of the Consumer is to consume the data from the buffer.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 49


The Producer / Consumer Problem

The following are the problems that might occur in the Producer-Consumer:
• The producer should produce data only when the buffer is not full. If the buffer is full, then the
producer shouldn't be allowed to put any data into the buffer.

• The consumer should consume data only when the buffer is not empty. If the buffer is empty,
then the consumer shouldn't be allowed to take any data from the buffer.

• The producer and consumer should not access the buffer at the same time.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 50


The Producer / Consumer Solution

In the producer-consumer problem, we use three semaphore variables:


1.Semaphore S: This semaphore variable is used to achieve mutual exclusion between processes.
By using this variable, either Producer or Consumer will be allowed to use or access the shared
buffer at a particular time. This variable is set to 1 initially.
2.Semaphore E: This semaphore variable is used to define the empty space in the buffer. Initially,
it is set to the whole space of the buffer i.e. "n" because the buffer is initially empty.
3.Semaphore F: This semaphore variable is used to define the space that is filled by the producer.
Initially, it is set to "0" because there is no space filled by the producer initially.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 51


The Producer / Consumer Solution

Problem Statement – We have a buffer of fixed size. A producer can produce an item and can place
in the buffer. A consumer can pick items and can consume them. We need to ensure that when a
producer is placing an item in the buffer, then at the same time consumer should not consume any
item. In this problem, buffer is the critical section.
To solve this problem, we need two counting semaphores – Full and Empty.
“Full” keeps track of number of items in the buffer at any given time and
“Empty” keeps track of number of unoccupied slots.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 52


The Producer / Consumer Solution

Solution
To solve this problem, we need two counting semaphores – Full and Empty.
“Full” keeps track of number of items in the buffer at any given time and
“Empty” keeps track of number of unoccupied slots.
Intialize
Mutex = 1
full = 0 // intially all slots are empty. Thus full slots are 0
empty = n // All slots are empty intially

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 53


The Producer Solution

do{ • When producer produces an item then the value of “empty” is reduced by
1 because one slot will be filled now.
• The value of mutex is also reduced to prevent consumer to access the
//produce an item buffer.
• Now, the producer has placed the item and thus the value of “full” is
wait(empty); increased by 1.
wait(mutex); • The value of mutex is also increased by 1 because the task of producer has
been completed and consumer can access the buffer.
//place in buffer

signal(mutex);
signal(full);

}while(true)

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 54


Consumer Solution

do{ • As the consumer is removing an item from buffer, therefore the value of
“full” is reduced by 1 and
• The value is mutex is also reduced so that the producer cannot access the
wait(full); buffer at this moment.
wait(mutex); • Now, the consumer has consumed the item, thus increasing the value of
“empty” by 1.
// remove item from • The value of mutex is also increased so that producer can access the buffer
buffer now.

signal(mutex);
signal(empty);

// consumes item

}while(true)
3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 55
Lamport Bakery solution

The Bakery algorithm is one of the simplest known solutions to the mutual exclusion
problem for the general case of N process.
Bakery Algorithm is a critical section solution for N processes.
The algorithm preserves the first come first serve property.
•Before entering its critical section, the process receives a number. Holder of the
smallest number enters the critical section.
•If processes Pi and Pj receive the same number
•The numbering scheme always generates numbers in increasing order of
enumeration; i.e., 1, 2, 3, 3, 3, 3, 4, 5, …

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 56


Lamport Bakery solution: Algorithm

Explanation –
Firstly the process sets its “choosing” variable to
be TRUE indicating its intent to enter critical
section.
Then it gets assigned the highest ticket number
corresponding to other processes.
Then the “choosing” variable is set to FALSE
indicating that it now has a new ticket number.
This is in-fact the most important and confusing
part of the algorithm.
It is actually a small critical section in itself !

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 57


Lamport Bakery solution: Algorithm

• Explanation –
The very purpose of the first three lines is that
if a process is modifying its TICKET value
then at that time some other process should not
be allowed to check its old ticket value which
is now obsolete.
• This is why inside the for loop before checking
ticket value we first make sure that all other
processes have the “choosing” variable as
FALSE.
• After that we proceed to check the ticket
values of processes where process with least
ticket number/process id gets inside the critical
section. The exit section just resets the ticket
value to zero.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 58


Test and Set Operation
Definition of the test and set() instruction.

The essential characteristic is that this instruction is executed atomically. So, if two Test And Set
(C) instructions are executed simultaneously (each on a different CPU), they will be executed
sequentially in some arbitrary order. we can implement mutual exclusion by declaring a Boolean
variable lock, initialized to false, if the machine supports the Test And Set () instruction. The
structure of process P, is shown in below.

Example
do {
while (test and set(&lock)) ;
/* do nothing */
/* critical section */
lock = false;
/* remainder section */
}
while (true);

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 59


Test and Set Operation
Scene-01: •The returned value 1 does not break the while loop
condition.
•Process P0 arrives. •The process P1 is trapped inside an infinite while loop.
•It executes the test-and-set(Lock) instruction. •The while loop keeps the process P1 busy until the lock
•Since lock value is set to 0, so it returns value 0 to the value becomes 0 and its condition breaks.
while loop and sets the lock value to 1.
•The returned value 0 breaks the while loop condition. Scene-03:
•Process P0 enters the critical section and executes.
•Now, even if process P0 gets preempted in the middle, no •Process P0 comes out of the critical section and sets the
other process can enter the critical section. lock value to 0.
•Any other process can enter only after process •The while loop condition breaks.
P0 completes and sets the lock value to 0. •Now, process P1 waiting for the critical section enters the
critical section.
Scene-02: •Now, even if process P1 gets preempted in the middle, no
other process can enter the critical section.
•Another process P1 arrives. •Any other process can enter only after process
•It executes the test-and-set(Lock) instruction. P1 completes and sets the lock value to 0.
•Since lock value is now 1, so it returns value 1 to the while
loop and sets the lock value to 1.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 60


Event Counters

The Event Counter counts transitions of the clock source and the gating mechanism is simply an
enable switch telling it to either count or ignore the signal. Upon initialization, the count is set to
zero counts and increments plus one on each clock transition. In the simplest form it counts and can
be reset to zero.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 61


Monitors
The monitor is one of the ways to achieve Process synchronization. The monitor is supported by
programming languages to achieve mutual exclusion between processes. For example Java
Synchronized methods. Java provides wait() and notify() constructs.

1.It is the collection of condition variables and procedures combined together in a special kind of
module or a package.
2.The processes running outside the monitor can’t access the internal variable of the monitor but can
call procedures of the monitor.
3.Only one process at a time can execute code inside monitors.
Syntax:
Wait operation
x.wait() : Process performing wait operation on any condition variable are suspended. The
suspended processes are placed in block queue of that condition variable.
Note: Each condition variable has its unique block queue.

Signal operation
x.signal(): When a process performs signal operation on condition variable, one of the blocked
processes is given chance.
3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 62
Message Passing
Message Passing Model
Multiple processes can read and write data to the message
queue without being connected to each other. Messages
are stored on the queue until their recipient retrieves them.
Message queues are quite useful for interprocess
communication and are used by most operating systems.

Advantage of Messaging Passing Model


The message passing model is much easier to implement
than the shared memory model.

Disadvantage of Messaging Passing Model


The message passing model has slower communication
than the shared memory model because the connection
setup takes time.

A diagram that demonstrates the shared memory model


and message passing model is given as follows −
3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 63
Classical IPC Problems
• Reader’s & Writer Problem
The readers-writers problem is used to manage synchronization so that there are no problems
with the object data. For example - If two readers access the object at the same time there is no
problem. However if two writers or a reader and writer access the object at the same time,
there may be problems.
Reader Process Writer Process

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 64


Classical IPC Problems
• Dinning Philosopher Problem
• Five philosophers sit around a table with five forks and spaghetti to eat.
• Philosophers think for a while and they want to eat, only spaghetti, for a while.
• To eat a philosopher requires two forks, one from the left and one from right.
• Assume a philo. can only pick up one fork at a time.
• After eating, forks are placed down and philo. goes back to thinking.
• Devise an algorithm that will allow philosophers to eat. Must satisfy mutual exclusion - no
two philoshpers can use the same fork at the same time. Avoid deadlock and starvation!

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 65


Classical IPC Problems
• Dinning Philosopher Problem
• First attempt: take left fork, then take right fork
Wrong! Results in deadlock.
• Second attempt: take left fork, check to see if
right is available, if not put left one down.
• Still has race condition and can lead to
starvation.
• Change so wait a random time. Will work
usually, but want a solution that will always
work, guaranteed.
• One solution is to protect obtaining forks with
a binary semaphore (mutex) - but only one
philo can eat at a time rather than two.
• Following code uses one semaphore per philo
and states of eating, thinking, and hungry. A
philo can advance to eating if neither neighbor
is eating.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 66


Classical IPC Problems
• Dinning Philosopher Problem

#define N 5 /* number of philos */


#define LEFT (i+N-1)%N /* # of i's left */
#define RIGHT (i+1)%N /* # of i's right */
#define THINKING 0
#define HUNGRY 1
#define EATING 2
int state[N]; /* keep track of state */
semaphore mutex = 1; semaphore s[N]; /* semaphore per philo *

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 67


Classical IPC Problems
• Dinning Philosopher Problem

void philosopher(int i)
{
while (TRUE)
{
think(); /* thinking */
take_forks(i); /* get two forks, block */
eat(); /* eating */
put_forks(i); /* give up forks */
}
}

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 68


Classical IPC Problems
• Dinning Philosopher Problem

void take_forks(int i)
{
wait(mutex);
state[i] = HUNGRY;
test(i); // try getting 2
forks signal(mutex);
if state[i] != EATING
wait(s[i]); // block if no forks acquired
}

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 69


Classical IPC Problems
• Dinning Philosopher Problem

void test(int i)
{
if ( state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] !=
EATING )
{
state[i] = EATING;
signal(s[i]);
}
}

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 70


Classical IPC Problems
• Dinning Philosopher Problem

void put_forks(int i)
{
wait(mutex);
state[i] = THINKING;
test(LEFT);
test(RIGHT);
signal(mutex);
}

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 71


Sleeping Barber Barber shop

• Sleeping Barber Barber shop with one barber, one barber chair and N chairs to wait in.
• When no customers the barber goes to sleep in barber chair and must be woken when a
customer comes in.
• When barber is cutting hair new customers take empty seats to wait, or leave if no vacancy.
• Program barber and customers so no race condition exists.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 72


Sleeping Barber Barber shop

• The following code uses 3 semaphores.


• - customers – number of waiting custs
• - barbers number of barbers (0 or 1) that are idle
• - mutex

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 73


Sleeping Barber Barber shop

#define CHAIRS 5 /* # of chairs */


semaphore customers = 0; //no of customers//
semaphore barbers = 0; //barber is free or busy//
semaphore mutex = 1;
int waiting = 0; //no of waiting customers//

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 74


Sleeping Barber Barber shop

void barber()
{
while (TRUE)
{
wait(customers); // barber is waiting for customer if there is no customer he asleep//
wait(mutex);
waiting = waiting – 1;
signal(barbers);
signal(mutex); cut_hair();
}
} Sleeping Barb

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 75


Sleeping Barber Barber shop

void customer()
{
wait(mutex);
if ( waiting < CHAIRS )
{
waiting = waiting + 1;
signal(customers);
signal(mutex);
wait(barbers);
get_haircut();
}
else
{ signal (mutex); }
}

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 76


Inter Process Communication Models and Schemes
Inter process communication is the mechanism provided by the operating system that allows processes
to communicate with each other. This communication could involve a process letting another process
know that some event has occurred or transferring of data from one process to another.

A diagram that illustrates inter process communication is as follows −

Inter process Communication

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 77


Inter Process Communication Models and Schemes
The models of inter process communication are as follows −

Shared Memory Model


Shared memory is the memory that can be simultaneously accessed by multiple processes. This is
done so that the processes can communicate with each other. All POSIX systems, as well as Windows
operating systems use shared memory.

Advantage of Shared Memory Model


Memory communication is faster on the shared memory model as compared to the message passing
model on the same machine.

Disadvantages of Shared Memory Model


Some of the disadvantages of shared memory model are as follows −

All the processes that use the shared memory model need to make sure that they are not writing to the
same memory location.
Shared memory model may create problems such as synchronization and memory protection that need
to be addressed.
3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 78
Process Generation

The 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 on the basis of a particular
strategy.
Process scheduling is an essential part of a Multiprogramming operating systems. Such operating
systems allow more than one process to be loaded into the executable memory at a time and the
loaded process shares the CPU using time multiplexing.
Categories of Scheduling
There are two categories of scheduling:
1.Non-preemptive: Here the resource can’t be taken from a process until the process completes
execution. The switching of resources occurs when the running process terminates and moves to a
waiting state.
2.Preemptive: Here the OS allocates the resources to a process for a fixed amount of time. During
resource allocation, the process switches from running state to ready state or from waiting state to
ready state. This switching occurs as the CPU may give priority to other processes and replace the
process with higher priority with the running process.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 79


Deadlock(CO3)

•In a multiprogramming system, processes request resources. If those resources are


being used by other processes then the process enters a waiting state. However, if other
processes are also in a waiting state, we have deadlock.

•A set of processes is in a deadlock state if every process in the set is waiting for an
event (release) that can only be caused by some other process in the same set.
Example
-System has 2 disk drives
-P1 and P2 process each hold one disk drive and each needs another one

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 80


Deadlock Characterization(CO3)

Deadlock can arise if four conditions hold simultaneously

1. Mutual exclusion: only one process at a time can use a resource .

2. Hold and wait: a process holding at least one resource is waiting to acquire additional resources
held by other processes .

3. No preemption: a resource can be released only voluntarily by the process holding it, after that
process has completed its task .

4. Circular wait: there exists a set {P0, P1, …, Pn} of waiting processes such that P0 is waiting
for a resource that is held by P1, P1 is waiting for a resource that is held by P2, …, Pn–1 is
waiting for a resource that is held by Pn, and Pn is waiting for a resource that is held by P0.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 81


Resource-Allocation Graph(CO3)

A resource allocation graph is a set of vertices V and a set of edges E such that:
•V is partitioned into two types:
P = {P1, P2, …, Pn}, the set consisting of all the processes in the system
R = {R1, R2, …, Rm}, the set consisting of all resource types in the system

•request edge – directed edge Pi → Rj


•assignment edge – directed edge Rj → Pi

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 82


Resource-Allocation Graph(CO3)

• Process

• Resource Type with 4 instances

• Pi requests instance of Rj
Pi

• Pi is holding an instance of Rj

Pi

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 83


Resource Allocation Graph With A Deadlock(CO3)

Before P3 requested an After P3 requested an


instance of R2 instance of R2

A Cycle In the Graph May cause Deadlock

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 84


Summary(CO3)

•If graph contains no cycles  no deadlock


•If graph contains a cycle 
•if only one instance per resource type, then deadlock
•if several instances per resource type, possibility of deadlock

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 85


Methods for Handling Deadlocks(CO3)

 Prevention
◦ Ensure that the system will never enter a deadlock state
 Avoidance
◦ Ensure that the system will never enter an unsafe state
 Detection
◦ Allow the system to enter a deadlock state and then recover
 Do Nothing
◦ Ignore the problem and let the user or system administrator respond to
the problem; used by most operating systems, including Windows and
UNIX

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 86


Deadlock Prevention(CO3)
To prevent deadlock, do not allow one of the four conditions to occur
1. Mutual Exclusion :

• if no resource were ever assigned to a single process exclusively ,we would never have deadlock.

• Shared entities (read only files) don't need mutual exclusion (and aren’t susceptible to deadlock.)

• Prevention not possible, since some devices are naturally non-sharable

2. Hold And Wait :


we must guarantee that whenever a process requests a resource, it does not hold any other resources

• Require a process to request and be allocated all its resources before it begins execution

• allow a process to request resources only when the process has none

Result: Low resource utilization; starvation possible


3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 87
Deadlock Prevention(CO3)
3. No Preemption :

• If a process that is holding some resources requests another resource that cannot be immediately
allocated to it, then all resources currently being held are released
• Pi → Rj → Pj → Rk
• A process will be restarted only when it can regain its old resources, as well as the new ones that it
is requesting.
• Allow preemption - if a needed resource is held by another process, which is also waiting on some
resource, steal it. Otherwise wait.

4. Circular Wait :

• To violate circular wait, we can assign a priority number to each of the resource. A process can't
request for a lesser priority resource. This ensures that not a single process can request a resource
which is being utilized by some other process and no cycle will be formed.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 88


Deadlock Avoidance(CO3)

• Requires that the system has some additional a priori information available.

• Simplest and most useful model requires that each process declare the maximum number of resources
of each type that it may need.

• The deadlock-avoidance algorithm dynamically examines the resource-allocation state to ensure that
there can never be a circular-wait condition.

• Resource-allocation state is defined by the number of available and allocated resources, and the
maximum demands of the processes.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 89


Safe State(CO3)
• When a process requests an available resource, system must decide if immediate allocation leaves
the system in a safe state

• System is in safe state if there exists a sequence <P1, P2, …, Pn> of all the processes in the
systems such that for each Pi, the resources that Pi can still request can be satisfied by currently
available resources + resources held by all the Pj, with j < I

That is:
• If Pi resource needs are not immediately available, then Pi can wait until all Pj have finished

• When Pj is finished, Pi can obtain needed resources, execute, return allocated resources, and
terminate

• When Pi terminates, Pi +1 can obtain its needed resources, and so on

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 90


Safe State(CO3)

• If a system is in safe state  no deadlocks

• If a system is in unsafe state  possibility of deadlock

• Avoidance  ensure that a system will never enter an unsafe


state.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 91


Avoidance algorithms(CO3)

• For a single instance of a resource type, use a resource-allocation graph


• For multiple instances of a resource type, use the banker’s algorithm

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 92


Resource-Allocation Graph with Claim Edges(CO3)

Assignment
edge Request
edge

Claim Claim
edge edge

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 93


Unsafe State In Resource-Allocation Graph (CO3)

Assignment
edge Request
edge

Assignment
Claim edge
edge

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 94


Resource-Allocation Graph Algorithm(CO3)

• Suppose that process Pi requests a resource Rj

• The request can be granted only if converting the request edge to an assignment edge does not result
in the formation of a cycle in the resource allocation graph

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 95


Banker’s Algorithm(CO3)

• Multiple instances
• Each process must a priori claim maximum use
• When a process requests a resource it may have to wait
• When a process gets all its resources it must return them in a finite amount of time

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 96


Data Structures for the Banker’s Algorithm (CO3)
Let n = number of processes, and m = number of resources types.
•Available: Vector of length m. If available [j] = k, there are k instances of
resource type Rj available.

•Max: n x m matrix. If Max [i,j] = k, then process Pi may request at most k


instances of resource type Rj.

•Allocation: n x m matrix. If Allocation[i,j] = k then Pi is currently allocated


k instances of Rj.
•Need: n x m matrix. If Need[i,j] = k, then Pi may need k more instances of
Rj to complete its task.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 97


Safety Algorithm(CO3)
1.Let Work and Finish be vectors of length m and n, respectively.
Initialize:
Work = Available
Finish [i] = false for i = 0, 1, …, n- 1

2.Find an i such that both:


(a) Finish [i] = false
(b) Needi  Work
If no such i exists, go to step 4

3. Work = Work + Allocationi


Finish[i] = true
go to step 2

4.If Finish [i] == true for all i, then the system is in a safe state

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 98


Resource-Request Algorithm for Process Pi(CO3)
Requesti = request vector for process Pi. If Requesti [j] = k then process Pi wants k instances of
resource type Rj

1. If Requesti  Needi go to step 2. Otherwise, raise error condition, since process has
exceeded its maximum claim
2. If Requesti  Available, go to step 3. Otherwise Pi must wait, since resources are not
available
3. Pretend to allocate requested resources to Pi by modifying the state as follows:
Available = Available – Requesti;
Allocationi = Allocationi + Requesti;
Needi = Needi – Requesti;
•If safe  the resources are allocated to Pi
•If unsafe  Pi must wait, and the old resource-allocation state is restored

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 99


Example of Banker’s Algorithm(CO3)
• 5 processes P0 through P4;
3 resource types:
A (10 instances), B (5 instances), and C (7 instances)
• Snapshot at time T0:
Allocation Max Available
ABC ABC ABC
P0 010 753 332
P1 200 322
P2 302 902
P3 211 222
P4 002 433

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 100
Example (Cont.)(CO3)

• The content of the matrix Need is defined to be Max – Allocation

Need
ABC
P0 743
P1 122
P2 600
P3 011
P4 431

• The system is in a safe state since the sequence < P1, P3, P4, P2, P0>
satisfies safety criteria

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 101
Example: (CO3)
P1 Request (1,0,2)
• Check that Request  Available (that is, (1,0,2)  (3,3,2)  true
Allocation Need Available
ABC ABC ABC
P0 010 743 230
P1 302 020
P2 302 600
P3 211 011
P4 002 431

• Executing safety algorithm shows that sequence < P1, P3, P4, P0, P2> satisfies safety
requirement

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 102
Deadlock Detection(CO3)

•Allow system to enter deadlock state


•Detection algorithm
•Recovery scheme

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 103
Single Instance of Each Resource Type(CO3)

•Maintain wait-for graph


•Nodes are processes
•Pi → Pj if Pi is waiting for Pj

•Periodically invoke an algorithm that searches for a cycle in the graph. If


there is a cycle, there exists a deadlock

•An algorithm to detect a cycle in a graph requires an order of n2


operations, where n is the number of vertices in the graph

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 104
Single Instance of Each Resource Type(CO3)

Resource-Allocation Graph Corresponding wait-for graph

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 105
Several Instances of a Resource Type(CO3)

•Available: A vector of length m indicates the number of available resources of each type
•Allocation: An n x m matrix defines the number of resources of each type currently allocated
to each process
•Request: An n x m matrix indicates the current request of each process. If Request [i][j] = k,
then process Pi is requesting k more instances of resource type Rj.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 106
Detection Algorithm(CO3)

1. Let Work and Finish be vectors of length m and n, respectively


Initialize:
(a) Work = Available
(b) For i = 1,2, …, n, if Allocationi  0, then
Finish[i] = false; otherwise, Finish[i] = true
2. Find an index i such that both:
(a) Finish[i] == false
(b) Requesti  Work
If no such i exists, go to step 4
3. Work = Work + Allocationi
Finish[i] = true
go to step 2
4. If Finish[i] == false, for some i, 1  i  n, then the system is in
deadlock state. Moreover, if Finish[i] == false, then Pi is deadlocked

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 107
Recovery from Deadlock(CO3)

Process Termination :

•Abort all deadlocked processes


•Abort one process at a time until the deadlock cycle is eliminated

In which order should we choose to abort?


1. Priority of the process
2. How long process has computed, and how much longer to
completion
3. Resources the process has used
4. Resources process needs to complete
5. How many processes will need to be terminated
6. Is process interactive or batch?

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 108
Recovery from Deadlock(CO3)

Resource Preemption :

•Selecting a victim – minimize cost

•Rollback – return to some safe state, restart process for that state

•Starvation – same process may always be picked as victim, include


number of rollback in cost factor

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 109
Concurrent Processing
• Concurrent processing is a computing model in which multiple processors execute instructions
simultaneously for better performance.
• Concurrent means, which occurs when something else happens.
• The tasks are broken into sub-types, which are then assigned to different processors to perform
simultaneously, sequentially instead, as they would have to be performed by one processor.
• Concurrent processing is sometimes synonymous with parallel processing.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 110
Concurrent Process
• Multiprogramming Environment :
In multiprogramming environment, there are multiple tasks shared by one processor. while a
virtual concert can be achieved by the operating system, if the processor is allocated for each
individual task, so that the virtual concept is visible if each task has a dedicated processor. The
multilayer environment shown in figure.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 111
Concurrent Process
• Multiprocessing Environment :
In multiprocessing environment two or more processors are used with shared memory. Only one
virtual address space is used, which is common for all processors. All tasks reside in shared
memory. In this environment, concurrency is supported in the form of concurrently executing
processors. The tasks executed on different processors are performed with each other through
shared memory. The multiprocessing environment is shown in figure.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 112
Concurrent Process
• Distributed Processing Environment :
In a distributed processing environment, two or more computers are connected to each other by a
communication network or high speed bus. There is no shared memory between the processors
and each computer has its own local memory. Hence a distributed application consisting of
concurrent tasks, which are distributed over network communication via messages. The
distributed processing environment is shown in figure.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 113
Monitor (CO3)
• It is a synchronization technique that enables threads to mutual exclusion and the wait() for a given
condition to become true. It is an abstract data type.

• It has a shared variable and a collection of procedures executing on the shared variable. A process
may not directly access the shared data variables, and procedures are required to allow several
processes to access the shared data variables simultaneously.

• At any particular time, only one process may be active in a monitor. Other processes that require
access to the shared variables must queue and are only granted access after the previous process
releases the shared variables.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 114
Advantages and Disadvantages of Monitor (CO3)
Advantages
1.Mutual exclusion is automatic in monitors.
2.Monitors are less difficult to implement than semaphores.
3.Monitors may overcome the timing errors that occur when semaphores are used.
4.Monitors are a collection of procedures and condition variables that are combined in a special type
of module.

Disadvantages

1.Monitors must be implemented into the programming language.


2.The compiler should generate code for them.
3.It gives the compiler the additional burden of knowing what operating system features is available
for controlling access to crucial sections in concurrent processes.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 115
Summary

Concurrent processes, precedence graphs, Critical Section, Race Conditions, Mutual Exclusion,
Hardware Solution, Semaphores, Strict Alternation, Peterson’s Solution, The Producer /
Consumer
Problem, Peterson’s solution, Lamport Bakery solution, Semaphores, Test and Set operation
Event
Counters, Monitors, Message Passing, Classical IPC Problems: Reader’s & Writer Problem,
Dinning
Philosopher Problem, Barber’s shop problem, Inter Process Communication models and
Schemes,
Process generation.
Definition, Necessary and sufficient conditions for Deadlock, Deadlock Prevention, Deadlock
Avoidance: Banker’s algorithm, Deadlock detection and Recovery.
Concurrent Programming: Critical region, conditional Critical region, Monitors, Concurrent
languages,
Communicating Sequential Process (CSP); Deadlocks - prevention, avoidance, detection and
recovery.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 116
Daily Quiz
1. A solution to the problem of indefinite blockage of low – priority processes is ____________
A. Starvation
B. Wait queue
C. Ready queue
D. Aging
2. Round robin scheduling falls under the category of ____________
A. Non-preemptive scheduling
B. Preemptive scheduling
C. All of the mentioned
D. None of the mentioned

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 117
Daily Quiz
3. The processes that are residing in main memory and are ready and waiting to execute are kept
on a list called _________

A. job queue
B. ready queue
C. execution queue
D. process queue

4. In priority scheduling algorithm ____________

A. CPU is allocated to the process with highest priority


B. CPU is allocated to the process with lowest priority
C. Equal priority processes can not be scheduled
D. None of the mentioned

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 118
Daily Quiz
5. The interval from the time of submission of a process to the time of completion is termed as
____________
A. waiting time
B. turnaround time
C. response time
D. throughput

6. In the following cases non – preemptive scheduling occurs?


A. When a process switches from the running state to the ready state
B. When a process goes from the running state to the waiting state
C. When a process switches from the waiting state to the ready state
D. All of the mentioned

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 119
Daily Quiz

7. Round robin scheduling falls under the category of ____________


A. Non-preemptive scheduling
B. Preemptive scheduling
C. All of the mentioned
D. None of the mentioned

8. Preemptive Shortest Job First scheduling is sometimes called ____________


A. Fast SJF scheduling
B. EDF scheduling – Earliest Deadline First
C. HRRN scheduling – Highest Response Ratio Next
D. SRTN scheduling – Shortest Remaining Time Next

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 120
Daily Quiz

9. Scheduling is done so as to ____________

A. increase CPU utilization


B. decrease CPU utilization
C. keep the CPU more idle
D. none of the mentioned

10. A solution to the problem of indefinite blockage of low – priority processes is ____________
A. Starvation
B. Wait queue
C. Ready queue
D. Aging

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 121
Weekly Assignment 3

• Differentiate between preemptive and non-preemptive scheduling.

• List out the necessary conditions for deadlock to occur..

• Define PCB

• List out the various scheduling criteria for CPU Scheduling.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 122
Faculty Video Links, Youtube & NPTEL Video Links and Online Courses Details

Unit 1 Unit 3
• https://www.youtube.com/watch?v=783 • https://www.youtube.com/watch?v=UczJ7misUEk
KAB-tuE4
• https://www.youtube.com/watch?v=_IxqinTs2Yo
• https://www.youtube.com/watch?v=Bxx
2_aQVeeg
• https://www.youtube.com/watch?v=Za Unit 4
GGKFCLNc0 • https://www.youtube.com/watch?v=IwESijQs9sM
• https://nptel.ac.in/courses/106/105/106 • https://www.youtube.com/watch?v=-orfFhvNBzY
105214/ • https://www.youtube.com/watch?v=2OobPx246zg
&list=PL3-wYxbt4yCjpcfUDz-
Unit 2 TgD_ainZ2K3MUZ&index=10
• https://www.youtube.com/watch?v=NS Unit 5
hBeqTkXnQ • https://www.youtube.com/watch?v=AnGOeYJCv6
• https://www.youtube.com/watch?v=4h • https://www.youtube.com/watch?v=U1Jpvni0Aak
Cih9eLc7M
• https://www.youtube.com/watch?v=9YR
xhlvt9Zo

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 123
MCQ
1. Which of the following scheduling algorithms gives minimum average waiting time?
A. FCFS
B. SJF
C. Round – robin
D. Priority

2. Which of the following condition is required for a deadlock to be possible?


A. mutual exclusion
B. a process may hold allocated resources while awaiting assignment of other resources
C. no resource can be forcibly removed from a process holding it
D. all of the mentioned

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 124
MCQ
3. A system is in a safe state only if there exists a ____________

A. safe allocation
B. safe resource
C. safe sequence
D. all of the mentioned

4. Given a priori information about the ________ number of resources of each type that maybe
requested for each process, it is possible to construct an algorithm that ensures that the system will
never enter a deadlock state.

A. Minimum
B. Average
C. Maximum
D. approximate

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 125
MCQ

5. The switching of the CPU from one process or thread to another is called ____________
A. process switch
B. task switch
C. context switch
D. all of the mentioned

6. If no cycle exists in the resource allocation graph ____________


A. then the system will not be in a safe state
B. then the system will be in a safe state
C. all of the mentioned
D. none of the mentioned

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 126
MCQ

7. The content of the matrix Need is _________

A. Allocation – Available
B. Max – Available
C. Max – Allocation
D. Allocation – Max

8. For a deadlock to arise, which of the following conditions must hold simultaneously?

A. Mutual exclusion
B. No preemption
C. Hold and wait
D. All of the mentioned

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 127
MCQ
9. Which of the following is not the state of a process?

A. New
B. Old
C. Waiting
D. Running

10. A single thread of control allows the process to perform __________


A. only one task at a time
B. multiple tasks at a time
C. only two tasks at a time
D. all of the mentioned

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 128
Glossary Questions

1. Fill in the blanks using following words


integer variable, critical section code, banker’s algorithm,starvation
a) Semaphore is a/an _______ to solve the critical section problem.
b) The code that changes the value of the semaphore is ____________
c) ______________ deadlock avoidance algorithm.
d) A problem encountered in multitasking when a process is perpetually denied
necessary resources is called ____________

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 129
Old Question Papers

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 130
Old Question Papers

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 131
Old Question Papers

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 132
Old Question Papers

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 133
Old Question Papers

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 134
Expected Questions for University Exam

1. Draw the labeled process state transition diagram with describing the various process states.

2. Write a note on Deadlock Prevention.

3. Explain Multi Level Queue Scheduling.

4. Explain Short term, Middle term and Long term Schedulers.

5. Write down the steps of Deadlock Detection

6. Define PCB.

7. List out the various scheduling criteria for CPU Scheduling.

8. List out the necessary conditions for deadlock to occur.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 135
Expected Questions for University Exam
9. Consider the following set of four processes, with the length of CPU
burst time given in milliseconds
Process Arrival Time Burst Time
P1 0 7
P2 2 4
P3 4 1
P4 5 4

Draw Gannt chart and find average waiting time and response time
using
• FCFS
• Round Robin (quantum=2)
• SJF and SRTF
3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 136
Expected Questions for University Exam

10. Let us consider the following snapshot


Allocation Max Available
ABC ABC ABC
P0 010 753 332
P1 200 322
P2 302 902
P3 211 222
P4 002 433

• What is the content of matrix need?


• Is the system in a safe state or not?
• If a request from process P1 arrives for (1,0,2) can request be
granted immediately or not?

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 137
Recap
Concurrent processes, precedence graphs, Critical Section, Race Conditions, Mutual Exclusion,
Hardware Solution, Semaphores, Strict Alternation, Peterson’s Solution, The Producer / Consumer
Problem, Peterson’s solution, Lamport Bakery solution, Semaphores, Test and Set operation Event
Counters, Monitors, Message Passing, Classical IPC Problems: Reader’s & Writer Problem,
Dinning
Philosopher Problem, Barber’s shop problem, Inter Process Communication models and Schemes,
Process generation.
Definition, Necessary and sufficient conditions for Deadlock, Deadlock Prevention, Deadlock
Avoidance: Banker’s algorithm, Deadlock detection and Recovery.
Concurrent Programming: Critical region, conditional Critical region, Monitors, Concurrent
languages,
Communicating Sequential Process (CSP); Deadlocks - prevention, avoidance, detection and
recovery.

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 138
References

Books :
1. Silberschatz, Galvin and Gagne, “Operating Systems Concepts”, Wiley
2. SibsankarHalder and Alex A Aravind, “Operating Systems”, Pearson Education
3. Harvey M Dietel, “ An Introduction to Operating System”, Pearson Education
4. D M Dhamdhere, “Operating Systems : A Concept basedApproach”, McGraw Hill.
5. Charles Crowley, “Operating Systems: A Design-Oriented Approach”, Tata McGraw Hill
Education”.
6. Stuart E. Madnick & John J. Donovan, “ Operating Systems”, Tata McGraw

3/13/2024 Ms. Rifa Nizam Khan ACSBS0403 Operating System Unit 3 139

You might also like