0% found this document useful (0 votes)
58 views108 pages

Unit-2 OS BCS-401

Uploaded by

mansviverma1881
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views108 pages

Unit-2 OS BCS-401

Uploaded by

mansviverma1881
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 108

Operating Systems

(BCS-401)

Process Synchronization
(UNIT-2)
Course Instructor:
Dr. Sanjeev Kumar
(Associate Professor, IT Department, KIET, Ghaziabad)
Operating Systems Syllabus (Unit-2)

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Process Synchronization
– Processes executing concurrently in the operating system may be either
independent processes or cooperating processes.

– A process is independent if it cannot affect or be affected by the other processes


executing in the system. Any process that does not share data with any other
process is independent.

– A process is cooperating if it can affect or be affected by the other processes


executing in the system. Clearly, any process that shares data with other
processes is a cooperating process.

– In this Unit we will discuss how concurrent or parallel execution can contribute
to issues involving the integrity of data shared by several processes
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Process Synchronization
– A cooperating process is one that can affect or be
affected by other processes executing in the
system.
– Concurrent access to shared data may result in
data inconsistency.
– The question is how concurrent or parallel
execution can contribute to issues involving the
integrity of data shared by several processes.
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Intercrosses Communication (IPC)
– Cooperating processes require an interprocess
communication (IPC) mechanism that will allow
them to exchange data and information.
– There are two fundamental models of interprocess
communication: shared memory and message
passing.

NOTE: In this chapter, we will focus on the issues


of shared memory environment.
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Shared Memory schemes for IPC

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Concept of cooperating processes (producer–consumer problem)
– Let’s understand the concept of Cooperating processes
by Producer–Consumer problem (a common paradigm
for cooperating processes).
– A producer process produces information that is
consumed by a consumer process.
– For example, a compiler may produce assembly code
that is consumed by an assembler. The assembler, in
turn, may produce object modules that are consumed by
the loader.
– Buffer could be bounded or unbounded (Producer free to
produce)
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Concept of cooperating processes (producer–consumer problem)
• Before Starting an explanation, first, understand
the few terms used in the code:
• in used in a producer code represent the
next empty buffer
• out used in consumer code represent first filled
buffer
• count keeps the count number of elements in
the buffer
• Fig: Buffer has total 8 spaces out of which the
first 5 are filled, in = 5 (pointing next empty
position) and out = 0 (pointing first filled
position), counter = 5.
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Producer Consumer

In : index to last empty Position, Out: First Filled Position in buffer.

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Concept of cooperating processes (producer–consumer problem)
– Although the producer and consumer routines shown
above are correct separately, they may not function
correctly when executed concurrently.
– Suppose that the value of the variable counter is currently
5 and that the producer and consumer processes
concurrently execute the statements “counter++” and
“counter--”.
– Following the execution of these two statements, the
value of the variable counter may be 4, 5, or 6! The only
correct result, though, is counter == 5
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
“counter++” and “counter- -” implementation in machine language
– counter++

– counter--

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
The concurrent execution of “counter++” and “counter--”

– Notice that we have arrived at the incorrect state “counter


== 4”, indicating that four buffers are full, when, in fact,
five buffers are full. If we reversed the order of the
statements at T4 and T5, we would arrive at the incorrect
state “counter == 6”.
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Race Condition
– We would arrive at this incorrect state because we allowed
both processes to manipulate the variable counter
concurrently.
– A situation like this, where several processes access and
manipulate the same data concurrently and the outcome of the
execution depends on the particular order in which the access
takes place, is called a race condition.
– To guard against the race condition above, we need to ensure
that only one process at a time can be manipulating the
variable counter. To make such a guarantee, we require that
the processes be synchronized in some way
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
The Critical-Section Problem
– Consider a system consisting of n processes {P0, P1, ...,
Pn-1}. Each process has a segment of code, called a
critical section, in which the process may be changing
common variables, updating a table, writing a file, and so
on.
– The important feature of the system is that, when one
process is executing in its critical section, no other
process is allowed to execute in its critical section. That
is, no two processes are executing in their critical
sections at the same time.
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
General structure of a typical process Pi
– Each process must request
permission to enter its critical
section.
– The section of code
implementing this request is
the entry section.
– The critical section may be
followed by an exit section.
– The remaining code is the
remainder section.
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Solution to the critical-section problem
– A solution to the critical-section problem must satisfy the following three requirements:
1. Mutual exclusion. If process Pi is executing in its critical section, then no other
processes can be executing in their critical sections.
2. Progress.
If no process is executing in its critical section and some processes wish to enter their
critical sections, then only those processes that are not executing in their remainder
sections can participate in deciding which will enter its critical section next, and this
selection cannot be postponed indefinitely. There should be no deadlock.
Here, Progress means that if one process doesn't need to execute into critical section
then it should not stop other processes to get into the critical section.
3. Bounded waiting. There exists a bound, or limit, on the number of times that other
processes are allowed to enter their critical sections after a process has made a
request to enter its critical section and before that request is granted.
4. No assumption regarding the underlying hardware(Platform independent).
Requirement 1 and 2 are mandatory for any solution of Critical section problem

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Solutions to Critical Section Problem
1. Software Based:(Lock Variable, Algorithm 1(Strict
alteration), Algorithm-2, Dekker’s solution, Peterson.
2. OS Based: Counting semaphore, Binary Semaphore
3. Hardware Based: Test and set Lock
4. Programming Language Compiler based: Monitors

Operating system(BCS401) (Dr.


Sanjeev Kumar, IT Department, KIET)
Critical section Using Lock Variable
• do{ • do{
Acquire lock
Critical Section 1. While(lock==1);
Release lock
} 2. Lock=1;
A shared variable
lock=0(initially) is
used, lock=1 means
3. Critical Section
busy, Lock=0 free.
4. Lock=0
Execute in user mode
Multiprocess(>1 or 2) solution
}
No MF
Operating system(BCS401) (Dr.
Sanjeev Kumar, IT Department, KIET)
Lock Variable: No Guarantee of Mutual
exclusion
• No guarantee of MF • do{
• P1, P2 process with lock=0
1. While(lock==1);
• P1 enters through line 1
• After that get interrupted 2. Lock=1;
after saving the state 3. Critical Section
• After this P2 tries to enter and find
The lock=0 so enters and gets into critical
4. Lock=0
Section, after P1 resumes with last known}
Value of lock=0, sets the value =1 and enters critical section. So two process
get into critical section.

Operating system(BCS401) (Dr.


Sanjeev Kumar, IT Department, KIET)
Proposed Solution Using Turn Variable [for two process]
Algorithm-1 (Strict alternation Method)

Operating system(BCS401)
Satisfies Mutual Exclusion, But(Dr.
Progress?
Sanjeev Kumar, IT Department,
KIET)
Strict Alternation: ME is Satisfied

Operating system(BCS401) (Dr.


Sanjeev Kumar, IT Department, KIET)
Strict Alternation: Progress not Satisfied

P0 might be in its remainder section at this time as it is not reentering CS to make turn=1.

Here a process in remainder section, and not interested to use Critical section is deciding when the
other process will enter in its critical section So Progress is not satisfied. .

Operating system(BCS401) (Dr.


Sanjeev Kumar, IT Department, KIET)
Two Process Solution: Algorithm-2

Operating system(BCS401) (Dr.


Satisfies Mutual Exclusion. What if Progress?
Sanjeev WhatKIET)
Kumar, IT Department, if both flag==True
Dekker’s Solution
– It is a software-based solution.
– Dekker's solution requires two shared variables:
turn and an array flag to indicate the intention of
each process.
– The flag variable for each process indicates
whether the process is interested in entering the
critical section.
– Dekker's solution is a classical algorithm but is
not suitable for modern multi-core systems.
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Final Dekker’s Solution to Critical Section Problem(Two Processes)
Pi Process Pj Process

Operating system(BCS401) (Dr.


Sanjeev Kumar, IT Department, KIET)
Peterson’s Solution
– A classic software-based solution to the critical-section
problem. It is also an simpler version of dekker.
– Peterson’s solution is restricted to two processes that alternate
execution between their critical sections and remainder
sections. I
– The processes are numbered P0 and P1. For convenience,
when presenting Pi, we use Pj to denote the other process;
that is, j equals 1 – i.
– Peterson’s solution requires the two processes to share two
data items:
int turn;
boolean flag[2];
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Peterson’s Solution
– The variable turn indicates whose turn it is to
enter its critical section. That is, if turn == i, then
process Pi is allowed to execute in its critical
section.
– The flag array is used to indicate if a process is
ready to enter its critical section. For example, if
flag[i] is true, this value indicates that Pi is ready
to enter its critical section.

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Structure of process Pi in Peterson’s solution

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Operating system(BCS401) (Dr.
Sanjeev Kumar, IT Department, KIET)
Peterson’s Solution: To enter the critical section
– 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 critical section, 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 eventual value of turn determines which of the two
processes is allowed to enter its critical section first.
– All the three requirements, i.e. mutual exclusion,
bounded waiting and progress is ensured in this solution.
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Key differences between Peterson's solution and Dekker's solution

• In Dekker's algorithm, the two processes seem to


be dominant. A process seems to force his way in
into the critical section unless it's the other one's
turn. Conversely, in Peterson's algorithm, the two
processes seem to be submissive and polite. If
both processes want to enter the critical section,
and it's the other one's turn, the process decides
to no longer want to enter.

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Locking( Test and Set)
• The hardware-based solution to critical section problem.
• There is shared lock variable which can take either value 0 or 1.
• 0 means is lock is free or unlocked, 1 means lock is engaged or locked.
• The solution implies that before entering into the critical section the
process must enquire about the lock status (Test the value)
• If it is locked it keeps on waiting till it become free.
• If not locked takes the lock(set value to 1) and executes the critical
section.
• Why hardware-based solution?
Because, hardware features can make any programming task easier and
improve system efficiency.

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Semaphores
• A semaphore S is an integer variable that, apart from
initialization, is accessed only through two standard atomic
operations: wait() and signal().
• The wait() operation is termed as P(to test); signal() is called
V(to increment).
• The definitions of wait() and signal() are as follows:

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Semaphores
• All modifications to the integer value of the semaphore is only done
through two standard wait() and signal() operations indivisibly.
• That is, when one process modifies the semaphore value, no other
process can simultaneously modify that same semaphore value.
• The definitions of the wait() and signal() semaphore
operations described here present the problem of Busy Waiting.

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Types of Semaphores
• The two common kinds of semaphores are
– Counting semaphores
– Binary semaphores
• A Binary Semaphore is a semaphore whose integer
value range over 0 and 1.(Initialized with 1)
• It is nothing, but similar to a lock, with two values: 0
and 1. Here 0 means busy, while 1 means free.
• The idea behind using a binary semaphore is that, it
allows only one process at a time to enter the
critical section(thus provides mutual exclusion).
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Types of Semaphores
• The two common kinds of semaphores are
– Counting semaphores
– Binary semaphores(also similar to mutex lock)
• A counting semaphore is a semaphore that has
multiple values of the counter. The value can
range over an unrestricted domain.
• The value of the counting semaphore can range
between 0 to N, where N is the number of
instances a shared resource has.
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Drawbacks of semaphores
• Busy waiting, i.e. while a process is in its critical section, any
other process that tries to enter its critical section, must loop
continuously in its entry code.

• Busy waiting wastes CPU cycles that some other process


might use to increase utilization.

• Such type of semaphore is called spinlock, because process


spins while waiting for lock.
Operating system(BCS401) (Dr.
Sanjeev Kumar, IT Department, KIET)
Semaphore Implementation with NO busy waiting
• We can modify the definition of the wait() and signal()
operations as follows:
• When a process executes the wait() operation and finds
that the semaphore value is not positive, it must wait.
• However, rather than engaging in busy waiting, the
process can block itself.
• The block operation places a process into a waiting
queue associated with the semaphore, and the state of
the process is switched to the waiting state.
• Then control is transferred to the CPU scheduler, which
selects another process to execute.
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Semaphore Implementation with NO busy waiting (Cont.)
• A process that is blocked, waiting on a semaphore S, should be
restarted when some other process executes a signal()
operation.
• The process is restarted by a wakeup() operation, which
changes the process from the waiting state to the ready state.
• To implement semaphores under this definition, we
define a semaphore as follows:

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Semaphore Implementation with NO busy waiting (Cont.)
Implementation of wait():
• When a process must wait on a semaphore, it is added
to the list of processes.

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Semaphore Implementation with NO busy waiting (Cont.)
Implementation of signal():
• A signal() operation removes one process from the list
of waiting processes and awakens that process.

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Semaphore Implementation with NO busy waiting (Cont.)
Points to remember
• The block() and the wakeup(P) operations are provided by the
operating system as basic system calls.
• It is critical that semaphore operations be executed atomically.
We must guarantee that no two processes can execute wait() and
signal() operations on the same semaphore at the same time.
• In this implementation, semaphore values may be negative,
whereas semaphore values are never negative under the classical
definition of semaphores with busy waiting.
• If a semaphore value is negative, its magnitude is the number of
processes waiting on that semaphore.
• To ensure bounded waiting, the list can be implemented as FIFO.
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Deadlocks and Starvation
• The implementation of a semaphore with a
waiting queue may result into a deadlocked
situation.
• To illustrate this, consider a system
consisting of two processes, P0 and P1,
each accessing two semaphores, S and Q,
set to the value 1: (NEXT SLIDE)
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Deadlocks and Starvation

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Classic Problems of Synchronization: The Bounded Buffer Problem
• The producer and consumer processes share the following
data structures:

• We assume that the pool consists of n buffers, each capable of


holding one item.
• The mutex semaphore provides mutual exclusion for accesses
to the buffer pool and is initialized to the value 1.
• The empty and full semaphores count the number of empty
and full buffers. The semaphore empty is initialized to the
value n; the semaphore full is initialized to the value 0.
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Classic Problems of Synchronization: The Bounded Buffer Problem
• The producer and consumer processes share the following
data structures:

• We assume that the pool consists of n buffers, each capable of


holding one item.
• The mutex semaphore provides mutual exclusion for accesses
to the buffer pool and is initialized to the value 1.
• The empty and full semaphores count the number of empty
and full buffers. The semaphore empty is initialized to the
value n; the semaphore full is initialized to the value 0.
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Classic Problems of Synchronization: The Bounded Buffer Problem
• The structure of the producer process

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Classic Problems of Synchronization: The Bounded Buffer Problem
• The structure of the consumer process

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Numerical Problem-1
• A counting semaphore S is initialized to 10.
Then, 6 P operations and 4 V operations are
performed on S. What is the final value of S?

Operating system(BCS401) (Dr.


Sanjeev Kumar, IT Department, KIET)
Solution-1
• P operation also called as wait operation decrements
the value of semaphore variable by 1.
• V operation also called as signal operation increments
the value of semaphore variable by 1.

Thus,
Final value of semaphore variable S
= 10 – (6 x 1) + (4 x 1)

Operating system(BCS401) (Dr.


Sanjeev Kumar, IT Department, KIET)
Problem-2
• A shared variable x, initialized to zero, is operated on by four concurrent processes W, X, Y, Z
as follows. Each of the processes W and X reads x from memory, increments by one, stores it
to memory and then terminates. Each of the processes Y and Z reads x from memory,
decrements by two, stores it to memory, and then terminates. Each process before reading x
invokes the P operation (i.e. wait) on a counting semaphore S and invokes the V operation
(i.e. signal) on the semaphore S after storing x to memory. Semaphore S is initialized to two.
What is the maximum possible value of x after all processes complete execution?

Operating system(BCS401) (Dr.


2 Sanjeev Kumar, IT Department, KIET)
Approach for Problem-2
1. First of all, make the process W read the
value of x = 0.
2. Then, preempt the process W.
3. Now, schedule process Y and process Z to
execute one by one.
4. After executing them, reschedule process
W.
5. Now, when process W gets scheduled
again, it starts with value x = 0 and
increments this value.
6. This is because before preemption it had
read the value x = 0.
7. The updates from the processes Y and Z
gets lost.
8. Later, execute process X which again
increments the value of x.
9. Here, the lost update problem has been
exploited.
[ Elaborate each step in detail as per process]

Operating system(BCS401) (Dr.


Sanjeev Kumar, IT Department, KIET)
Problem-3

Operating system(BCS401) (Dr.


Sanjeev Kumar, IT Department, KIET)
Solution-3
• 2nd and 3rd Choice
• Since S1=1 initially & both the threads are
performing operation on S1 So, only one thread
can succeed & run.
• If thread T1 runs first, then T1 gets blocked when
it executes wait(S2). Also,T2 cannot run as it
would get blocked when it executes wait(S1). So,
deadlock occurs.
Operating system(BCS401) (Dr.
Sanjeev Kumar, IT Department, KIET)
Problem-4: Find final value of a and b

Operating system(BCS401) (Dr.


1
Sanjeev Kumar, IT Department, KIET)
Problem-7: The following programs consist of 3 concurrent processes and 3
binary semaphores. The Binary semaphores are initialized as S0=1, S1=0,
S2=0.[In binary semaphore Note that signal operation sets value to 1 rather
incrementing, S=0/1]
Process P1 Process P2 Process P3
While(TRUE) Wait(S1); Wait(S2);
{ Release(S0); Release(S0);
Wait(S0);
Print(0);
Release(S1)
Release(S2)
}

How many time ‘0’ will be printed


1. At least twice
2. Exactly Twice
3. Exactly thrice
Operating system(BCS401) (Dr.
4. Exactly once Sanjeev Kumar, IT Department, KIET)
Test And Set Hardware Instruction
• This is hardware solution to synchronization problem
• There is a shared lock variable having value 0(Unlocked)/1(Locked).
• Before Entering critical section, process enquires about the lock( Called Testing Part) if
locked then keep on waiting for other process, till unlocked.
• If it is not locked then process takes the lock by setting lock=1(Setting), and enters
critical section.
• The TestAndSet() hardware instruction is atomic instruction.

ATOMIC
OPERATION

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Test And Set Hardware
Based Solution

Bounded wait not guaranteed

P1

P2-->

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
Mutual exclusion by TestandSet() KIET)
TestAndSet Hardware Instruction
• This solution lets only one process to execute its
critical section at a time. This is how it achieves
mutual exclusion.
• But this structure does not assure bounded wait as
it may happen that process P0 may keep on
executing its critical section again and again and
P1 has to keep on waiting due to preemption and
meanwhile 3rd process enters into critical section
before P1 Resumes( This case may arise).
• The progress requirement is met.
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Classic Problems of Synchronization:
Reader Writers Problem
• A shared database is there shared among different processes.
• Some process may read concurrently or Read and write to database
concurrently(i.e. Update. )
• The process that only want to read are readers, and processes that
want write are writers.
• This is called Reader-Writers problem.
• Shared data read by two reader don’t lead any problem.
• The problem is there, when writer and some other process(Reader or
writer)access database simultaneously.
can lead to inconsistency of data.

Operating system(BCS401) (Dr.


Sanjeev Kumar, IT Department, KIET)
Classic Problems of Synchronization: The Readers–Writers Problem
• We require that the writers have exclusive access to the
shared database while writing to the database.
• So we need make sure when writers are writing, no reader or
other writer should be allowed to access the shared database.
• The readers–writers problem has several variations:
– First readers–writers problem: no reader be kept waiting
unless a writer has already obtained permission to use the
shared object.
– Second readers–writers problem: once a writer is ready,
that writer perform its write as soon as possible.
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Solution to the First Readers–Writers Problem
• The reader processes share the following data structures:

• The semaphores mutex and rw_mutex are initialized to 1; read count is


initialized to 0.
• The semaphore rw_mutex is common to both reader and writer processes.
• The mutex semaphore is used to ensure mutual exclusion when the variable
read count is updated.
• The read count variable(not semaphore) keeps track of how many processes
are currently reading the object.
• The semaphore rw_mutex functions as a mutual exclusion semaphore for the
writers. It is also used by the first or last reader that enters or exits the
critical section.

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
The structure of a reader and writer processes
Lock to required to updated the read count

Atleast one reader is available, and that


to start reading
Allow other readers, as Simultaneous reading is
allowed

Lock to required to updated the read count

No Reader is Left in critical section


Writer Process To allow Writer
Last Reader Leaves

Reader Process

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Observations

• Note that, if a writer is in the critical section and n


readers are waiting, then one reader is queued on
rw mutex, and n - 1 readers are queued on mutex.
• Also observe that, when a writer executes
signal(rw mutex), we may resume the execution of
either the waiting readers or a single waiting
writer. The selection is made by the scheduler.

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Problem-5

Operating system(BCS401) (Dr.


Sanjeev Kumar, IT Department, KIET)
Solution-5

Operating system(BCS401) (Dr.


Sanjeev Kumar, IT Department, KIET)
Problem-6: Consider method used by Process P1 and P2 for accessing critical
sections whenever needed, The Initial value of shared variable S1 and S2 are
randomly assigned
Process P1 Process P2
While(S1==S2); While(S1!=S2);
CRITICAL SECTION CRITICAL SECTION
S1=S2; S1=NOT(S2);

WHICH OF FOLLOWING STATEMENT DESCRIBES THE PROPERTIES ACHIEVED

1. Mutual exclusion but not progress


2. Progress but not mutual exclusion
3. Neither Mutual exclusion nor Progress
4. Both mutual exclusion and Progress.

Operating system(BCS401) (Dr.


Sanjeev Kumar, IT Department, KIET)
Ans. A
After using critical section if P1 wants to enter
again and P2 do not want critical section, here
P1 will not be able to use critical section even
though being free so progress is not satisfied.

Operating system(BCS401) (Dr.


Sanjeev Kumar, IT Department, KIET)
Classical problem: Sleeping Barber Problem
• There is a barber shop with one barber and a number of chairs for
waiting customers. Customers arrive at random times and if there
is an available chair, they take a seat and wait for the barber to
become available. If there are no chairs available, the customer
leaves. When the barber finishes with a customer, he checks if
there are any waiting customers. If there are, he begins cutting
the hair of the next customer in the queue. If there are no
customers waiting, he goes to sleep.
• The problem is to write a program that coordinates the actions of
the customers and the barber in a way that avoids synchronization
problems, such as deadlock or starvation

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Sleeping Barber Problem : Solution using Semaphore

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT, KIET)
Sleeping Barber Problem: Analysis
• When the barber starts his shift, the barber procedure is carried
out, and he checks to see whether any clients are ready or not. Pick
up the client for a haircut and block the client's semaphore if
anybody is available. If nobody requests a haircut, the barber goes
to sleep.
• The customer releases the mutex, the barber wakes up, and the
waiting counter is increased if a chair becomes available. The
barber then enters the crucial portion, obtains the mutex, and
begins the haircut.
• The client departs when the haircut is finished. Now the barber
looks to see if there are any other clients waiting for a haircut or not
in the waiting area. The barber is going to sleep if it is not.
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
• Any Deadlock?
• Any possibility of starvation?

Operating system(BCS401) (Dr.


Sanjeev Kumar, IT Department, KIET)
The Dining-Philosophers Problem
• On round dining table five philosophers are sitting.
• Philosopher can be in two states. Either thinking or
Eating States.
• When any Philosopher is thinking they don’t interact
with their adjacent Philosophers.
• When they are hungry they will try to eat the food in
plate( Rice/ Noodle) using the two forks/Chop sticks
plates on their both sides. So they always need two
forks. Once two forks are taken they cannot taken
back unless placed back by eating philosophers.
• Problem is here is that there are 5 Philosophers and
only five forks.
• WE NEED TO ENSURE THAT NO TWO PHILOSOPHERS
WHO ARE SITTING ADJACENT TO EACH OTHER TRY
TO EAT AT THE SAME TIME THROUGH
SYNCHRONIZATION PRIMITIVES. OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
The Dining-Philosophers Problem Scenario

• Related to OS as it PHILOSOPHER

reflects limited
resources and problem IF THINKS IF EATS

of resource allocation. •Does not •Try to pick two forks,


interact Taking one at time.
• Philosophers-> •One cannot pick a
fork that already
Processes being used by other
•Once two forks are
• Forks Resources taken they cannot
taken back unless
placed back by eater
philosophers and
starts thinking again.
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
The Dining-Philosophers Problem SOLUTION using semaphores
• One simple solution is to represent each Fork/chopstick with a
semaphore.
• A philosopher tries to grab a Fork/chopstick by executing a wait()
operation on that semaphore.
• A philosopher releases her chopsticks by executing the signal() operation
on the appropriate semaphores.
• Thus, the shared data are
semaphore chopstick[5];
// array of semaphore type 5 element of [binary semaphores

All initialized to 1. i.e. free to use by any one initially.

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
The Dining-Philosophers Problem
• Any Possibility of deadlock?

The structure of philosopher i

Can two philosophers eat at same time. ?

Any Possibility of deadlock?

What if all gets hungry at same time.?

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
The Dining-Philosophers’s Dead lock Problem
• Deadlock may occur in given solution.
• Several possible remedies are as follows;
1. Allow at most four philosophers to be sitting.
2. Allow a philosopher to pick up her chopsticks only if
both chopsticks are available (to do this, she must pick
them up in a critical section).
3. Use an asymmetric solution—that is, an odd-numbered
philosopher picks up first her left chopstick and then her
right chopstick, whereas an even numbered philosopher
picks up her right chopstick and then her left chopstick.
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
The Dining-Philosophers Problem
• Solution to Deadlock;
• Any satisfactory solution to the dining-philosophers
problem must guard against the possibility that one of the
philosophers will starve to death.
• A deadlock-free solution does not necessarily eliminate
the possibility of starvation.

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Monitor: why?
• Incorrectly written Processes using semaphores can result in timing
errors that are difficult to detect.
• If this sequence of wait() & signal() operations is not observed, two
processes or threads may be in their critical sections
simultaneously.
• Examples
NO Mutual Exclusion Deadlock

CASE-1 CASE-2
• In these cases, either mutual exclusion is violated
OPERATING SYSTEMS (KCS-401)
orKumar,
(Dr. Sanjeev a deadlock will
Associate Professor, IT,
KIET)
Monitor
• To deal with such errors (previous slide), researchers have
developed high-level language construct; the monitor type.
• A monitor type is an ADT that includes a set of programmer-
defined operations that are provided with mutual exclusion
within the monitor.
• The monitor type also contains the declaration of variable
whose value define the state of instance of that type along
with bodies of functions/Procedures that operate on those
variables.

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Monitor: Structure and Requirement for synchronization
• Function defined within a monitor can
access only those variables declared
locally within the monitor and its formal
parameters.
• A Procedure defined within monitor can
access only those variable that are
defined locally within monitor and
formal parameters.
• Similarly local variable of a monitor can
only be accessed by only by local
procedures inside the monitor.
• The monitor construct ensures that only
one process at a time is active within the
monitor.
OPERATING SYSTEMS (KCS-40 va1)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Monitor Requirement : Condition Variable
• The monitor construct ensures that only
one process at a time is active within the
monitor.
• A programmer who needs to write a tailor-
made synchronization
scheme can define one or more variables
of type condition:
condition x, y;
• The only operations that can be invoked on
a condition variable are wait() and signal().
• The operation x.wait(); means that the
process invoking this operation is
suspended until another process invokes
x.signal(); which resumes one suspended
process. OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Schematic View
• Operations or procedures
to manipulate shared data.
• Initialization code to
initialize the variable.
• Queue associate With x
and y are used and
released according to wait
and signal operation.

Operating system(BCS401) (Dr.


Sanjeev Kumar, IT Department, KIET)
Dining-Philosophers Solution Using Monitors
• A deadlock-free solution to the dining-philosophers problem.
• This solution imposes the restriction that a philosopher may pick up her
chopsticks only if both of them are available.
• To code this solution, we need to distinguish among three states of philosopher
using the data structure;

• Philosopher i can set the variable state[i] = EATING only if her two neighbors are
not eating: (state[(i+4) % 5] != EATING) and (state[(i+1) % 5] != EATING).
• We also need to declare condition self[5]; where philosopher can delay himself
when he is hungry but is unable to obtain chopsticks he need

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
Dining-Philosophers Solution Using Monitors

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
89
Inter Process Communication (IPC)
Inter Process Communication (IPC) is a mechanism
that involves communication of one process with
another process.

A process can be of two type:


Independent process
Co-operative process

90
TYPES OF PROCESSES
 Independent Process:
 A process is independent if it cannot affect or be
affected by other processes executing in the system.
 Any process that does not share data with any other
process is independent.

 Co-operative Process:
 A process is Co-operative if it can affect or be
affected by other processes executing in the system.
 Any process that share data with any other process is
co-operative.
91
Reasons for providing an Environment
that allows process cooperation
1. Information Sharing: Several users may be interested in shared file.
There is a need to provide an environment so that the information can be
accessed concurrently.
2. Computational speedup: Task is divided into sub tasks that run
concurrently in order to achieve computational speedup. These subtasks
are the processes that communicate with each other.
3. Modularity: We want to design a system by dividing it into separate
modules. These modules communicate with each other and then put
together to achieve the goal.
4. Convenience: If we provide an environment that allow the processes to
cooperate with each other, then that becomes very convenient to the user.
Suppose a user may be using his system for doing several different tasks
at the same time. For example he may be writing document, listening
song or printing a document. So these tasks must be allowed to run
concurrently for smooth functioning of the system. 92
Inter Process Communication
Model (IPC Model)
• IPC means how two processes are communicate
to each other.
• Cooperative processes require an IPC
mechanism that will allow them to exchange
data and information.

• There are two fundamental models of Inter-


process Communication (IPC):
1. Shared Memory System
93
2. Message Passing System
Inter Process Communication
Model (IPC Model)

94
SHARED MEMORY SYSTEM
• In the shared memory model, a region of memory that is shared by co-
operating processes is established. Processes can then exchange information
by reading and writing data to the shared region.

EXAMPLE
• Suppose process A and process B are executing simultaneously and they share
some resources or use some information from other process,
• process A generate information about resources being used and keeps it as a
record in shared memory. When process B need to use the shared information,
it will check in the record stored in shared memory and take note of the
information generated by process A and act accordingly.
• Processes can use shared memory for extracting information as a record from
other process as well as for delivering any specific information to other
process. 95

NOTE: Producer-Consumer problem Uses Shared Memory Concepts


MESSAGE PASSING SYSTEM
• In the Message Passing model, communication takes place by means of
messages exchanged between the cooperating processes.
• There are several methods for logically implementing a link and
send( )/receive( ) operations.
send(message, destination) or send(message)
receive(message, host) or receive(message)

96
MESSAGE PASSING SYSTEM
• A standard message can have two parts: header and body.

• The header part is used for storing Message type, destination id,
source id, message length and control information.
• The control information contains information like what to do if runs out
of buffer space, sequence number, priority. Generally, message is sent
using FIFO style.
• There are two types of message passing communication are used:
1. Direct Communication
2. Indirect Communication

97
DIRECT MESSAGE PASSING

98
99
100
DIRECT MESSAGE PASSING

• Difficulty arises when name of any method or


process changes, this method need complex
updation for communication links that were
connected with the process due to which this
method is not suitable.

101
INDIRECT MESSAGE PASSING
• In indirect message passing , processes uses mailboxes ( also known as ports)
for sending and receiving messages. Each mailbox has a unique id.
• Suppose two processes want to communicate through Indirect message passing,
the required operations are : create a mail box, use this mail box for sending and
receiving messages, destroy the mail box.
• Operations are: send(A, message) means send the message to mailbox A.
receive(A, message) means receive message A from mailbox.
• A process can communicate with another process via a number of different
mailboxes, but two processes can communicate only if they have a shared
mailbox.
• A mailbox may be owned either by a process or by the operating system. If the
mailbox is owned by a process (that is, the mailbox is part of the address space of
the process), then we distinguish between the owner (which can only receive
messages through this mailbox) and the user (which can only send messages to
102
the mailbox)
103
104
105
Buffering In IPC

106
Process Generation: fork()
• Fork system call is used for creating a new process,
which is called child process, which runs concurrently
with the process that makes the fork() call (parent
process).
• After a new child process is created, both processes will
execute the next instruction following the fork() system
call.
• A child process uses the same pc(program counter), same
CPU registers, same open files which the parent process
is currently using.
OPERATING SYSTEMS (KCS-401)
(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
fork()
• Please note that the below programs don’t compile in Windows

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
fork() : Another Example

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
fork() : Child Creation
• The number of times ‘hello’ is printed is equal to number of
process created.
• Total Number of Processes = 2n, where n is number of fork system
calls. So here n = 3, 23 = 8 Let us put some label names for the
three lines:

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)
fork() : Tree hierarchy
• So there are total eight processes (seven
new child processes and one original
process).
• Tree hierarchy:
The main process: P0
Processes created by the 1st fork: P1
Processes created by the 2nd fork: P2, P3
Processes created by the 3rd fork: P4,
P5, P6, P7

OPERATING SYSTEMS (KCS-401)


(Dr. Sanjeev Kumar, Associate Professor, IT,
KIET)

You might also like