You are on page 1of 45

SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -

140702

UNIT-3
Content of Unit-3
Inter process Communication:

Race Conditions

Critical Section

Mutual Exclusion

Hardware Solution

Strict Alternation

Peterson’s Solution

The Producer Consumer Problem

Semaphores

Event Counters

Monitors, Message Passing.

 Classical IPC Problems: Reader’s & Writer Problem,
Dinning Philosopher Problem, Scheduling, Scheduling
Algorithms.

Grow More Faculty of Degree Engineering Page 1


SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -
140702

Inter Process Communication

Process frequently need to communicate with the other process.for example in


shell pipeline the output of the first process must be passed to the second
process and so on.there is neeed for communication between processes that is
called the inter process communication.

There are three issues for that


(1)How one process pass information to the other
process (2)Two or More Process Do not get Each other
ways (3)Proper Scheduling

RACE CONDITION

In Some Operating System ,process that working together may share some
common storage that each one can read and write.the storage may be in main
memory or it may be in shared memory .the location of shared memory do not
change the nature of communication works in practice,let us consider simple but
common examples:a print spooler .when a process wants to print a file ,it enters
the file in special spooler directories.

Imagine that spooler directory has a large number of slots ,number 0 to n each one
capable of holding the file name. Also imagine in and out variable

This is represent in the figure.if process A and process B are used same memory location
than there will be race between this two process to execute the output. Suppose Process A
first used share memory and execute the output but interrupt will occurs than process A
have to wait for a While and same time process B Can be use to the share Memory but
Process A awake and return to the memory and execute again and process B in terms of
that process execute but never get the output. so this situation is treat as race condition.
Race between two process condition is that process share a memory area

Race Condition:-When Two or processes are reading or writing the some shared
data and final result depends on who runs precisely when are called that is call
race condition. means which process execute first that depends the inter process
scheduling of that process.
Grow More Faculty of Degree Engineering Page 2
SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -
140702

Rules for Avoiding Race Conditions


1. No two processes may be simultaneously inside their critical sections
2. No assumptions may be made about the speeds or number of CPUs
3. No process running outside its critical section may block other processes
4. No process should have to wait forever to enter its critical section

CRITICAL SECTION
A Critical Section is a Sequence or block of code run by a thread/process. When one
process executes the critical region than no other process will allow
executing the critical region if these occurs than there will be chance of problem on critical
region. a solution of critical section must be follow the three requirements:
Grow More Faculty of Degree Engineering Page 3
SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -
140702

Solution of critical Section problem


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 there exist
some processes that wish to enter their critical section, then the selection of the
processes that will enter the critical section next cannot be postponed
indefinitely.
3. Bounded Waiting:-. A bound must exist 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.
Assume that each process executes at a nonzero speed. No assumption
concerning relative speed of the n processes.

 MUTUAL EXCLUSION
 A way of making sure that if one process is using a shared modifiable
data, the other processes will be excluded from doing the same thing.
 Formally, while one process executes the shared variable, all other processes
desiring to do so at the same time moment should be kept waiting; when that process
has finished executing the shared variable, one of the processes waiting; while that
process has finished executing the shared variable, one of the processes waiting to do
so should be allowed to proceed. In this fashion, each process executing the shared
data (variables) excludes all others from doing so simultaneously. This is called
Mutual Exclusion.
 Note that mutual exclusion needs to be enforced only when processes access
shared modifiable data - when processes are performing operations that do not conflict
with one another they should be allowed to proceed concurrently.

 SOLUTION TO MUTUAL EXCLUSION PROBLEM

(1)SOFTWARE SOL:-Dekkeres algo,Peterson algo,bakery’s algo

(2)HARDWARE SOL:-Special machine Instruction

(3)OS SOULTION:-Semaphores,Mutex
Grow More Faculty of Degree Engineering Page 4
SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: - 140702

(1)SOFTWARE SOLUTIONS
Software Approches can be implemented for current process that executes on a single
processor or multiprocessor machine with the shared main memory.

(1)DEKKER’S AlGORITHM:-This is the First known correct solution to


the mutual exclusion problem in current programming.
If two process attempt to enter critical section at the same time ,the algorithm
will allow only one process at time, based on whose turn it is.
This is done by using two variables flags flag[0],flag[1] which indicates an
intension to enter the critical region.and turn variable which indicates whose
has priority between the two process.

Flag[0]=false

Flag[1]=false

Turn = 0/1

Po P1

Flag[0]:-true Flag[1]:-true

While(flag[1]=true) While(flag[0]=true)

{ {

If turn!= 0 If turn!= 1

{ {

Flag[0]=false Flag[1]=false

While(turn!=0) While(turn!=1)

{ {

Grow More Faculty of Degree Engineering Page 5


SUBJECT CODE: -
SUBJECT NAME:-OPERATING SYSTEM 140702

} }

Flag[0]=true Flag[1]=true

} }

}//critical section //critical Section

Process indicates an intension to enter the critical region which is tested by outer
while loop if other process has not flagged intent, the critical region can be
entered safely irrespective of the current turn.

(2)Peterson’s Algorithm:-this is a concurrent programming for mutual exclusion


that allows two process to share a single use resources without conflict ,using only
shared memory for communication.

Flag[0]=0
Flag[1]=1
Turn;
P0 P1
Flag[0]=1 Flag[1]=1
turn=1 turn=0
While(flag[1]==1 && turn==1) While(flag[0]==1 && turn==0)
{ {
//busy wait //busy wait
} }
// critical section // critical section
….. ……
// end of critical section // end of critical section

The algorithm used two variables flag and turn.if the value of flag is 1 that
indicates that process want to enter in critical region .the variable turn holds the ID
of process whose turn it is.

Grow More Faculty of Degree Engineering Page 6


SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -
140702

If one process want to enter critical section and same time another process is
inside the critical region so the process becomes busy wait.
So at a time one process can use the critical region so there is no chance
for problem on scenario of mutual exclusion

(3)Lamport’s bakery Algorithm:-It is common for multiple thread to


simultaneously access the same resources. data corruption can occur if two or
more thread try to write into same memory location. or if one thread reads memory
location before another has finished writing into it.lamport’s bakery algorithm is
one of many mutual exclusion algorithm to design to prevent concurrent thread
entering in critical section of code concurrently eliminate the risk of data
corruption

This algo is based on analogy of bakery. a numbering machine its entrance so that
each customer is given a unique number .number is increase by one customer
enter into the store.

A Global Counter displays the number of customer that being saved.


All other customer must wait into queue until the baker’s finishes serving the
current customer and next number is display .when the customer is done
shopping and has disposed of his or her number, the clerk increment the number
allowing next customer to be served.
the customer must draw another number from the numbering machine in order
to shop again.

In Computer world the customer’s will be thread ,identify the letter I obtaind form
a global variable .it’s possible that more than one thread will get the same number
when they request it this cannot be avoid.
The critical section is that part of code that requires exclusive access to resources and
may only be executed by one thread at a time. In the bakery analogy, it is when the
customer trades with the baker and others must wait.
When a thread wants to enter the critical section, it has to check whether it is its turn
to do so. It should check the numbers of every other thread to make sure that it has the
smallest one. In case another thread has the same number, the thread with the smallest
i will enter the critical section first.
Grow More Faculty of Degree Engineering Page 7
SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -
140702

(2)HARDWARE SOLUTIONS
Special machine Instructions are the hardware solution for the mutual Exclusion

Test and set is one such a kind of instructions

The hardware solution is the use of machine instruction named test and set the
variables and to test the value and set it to a stipulated value

The test and set instruction can be define as follows

Function testset

begin

if i=0 then

begin

i=1

testset:=true

end

else testset:-false

end

Test_and_Set is a special assembly language instruction that does two operations


autonomously. That is, the instruction can not be interrupted in the middle and it is
not necessary to disable interrupts.
Grow More Faculty of Degree Engineering Page 8
SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -
140702

(3)OS SOLUTIONS
There are two os solution for problem of mutual exclusion is mutex
and semaphores
Semaphore:- this are a programming construct design by the dijkstra in the
late 1960 model was the operation of railroads
Consider the stretch of rail road in which single track over which only one train
at a time is allowed. Guarding the track is semaphore.
A Train must wait before entering the single track until the semaphore is in
state that permits travel.
When train enter the track than semaphore tries to prevent other train to enter into
the track.
In computer version semaphores apperes as a integer variable.the process or thread have to wait
to enter into the critical region until the integer variable becomes 0
Grow More Faculty of Degree Engineering Page 9
SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -
140702
Grow More Faculty of Degree Engineering Page 10
SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -
140702

MUTEX:-Mutexis like small token passing program. token is passed to the particular
process.process which have the token is access the critical region and after using the
critiacal section process must have to relase that token.

Token is nothing but the small integer variable.


Grow More Faculty of Degree Engineering Page 11
SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -
140702

CLASSICAL PROBLEM OF SYNCHRONIZATION


(1)BOUNDED BUFFER PRODUCER CONSUMER PROBLEM

(2)READERS AND WRITERS PROBLEM

(3)DINING PHILOSOPHER PROBLEM

(1)BOUNDED BUFFER PRODUCER CONSUMER PROBLEM

The Bounded Buffer problem was process synchronization concepts.

One of the simplest synchronization examples is the bounded buffer


problem, also known as the producer-consumer problem. Often, this
example is used to introduce the importance
of synchronization because of its wide applicability. Producer processes produce
items that are stored in a shared circular queue, while consumer processes remove
these items and process them. Synchronization is needed to guarantee that producers
do not insert items into the queue when the queue is full, that consumers do not try to
remove items when the queue is empty, and that each produced item is consumed by
exactly one consumer.
Unsynchronized versions of the producer and consumer loops are shown below.
The bounded buffer is implemented as a circular queue of size n. The number of
items stored in the queue is kept in counter while in and out point to the next empty
slot and the last full slot, respectively.
Producer:
nextp = produce();
while (counter == n) ;
buffer[in] = nextp;
in = (in + 1)%n;
counter++;
Consumer:
while (counter == 0) ;
nextc = buffer[out];
out = (out + 1)%n;
counter--;
consume(nextc);
When there is only one producer and one consumer on a single
Grow More Faculty of Degree Engineering Page 12
SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -
140702

CPU system, the code is correct as long as the incrementing and


decrementing of the counter is atomic. However, on most RISC
machines counter++ is implemented with three assembly
language instructions:
R1 = counter
R1 = R1 + 1
counter = R1
If the producer loses the CPU after the first or second of these instructions and the
consumer decrements the counter, the counter will end up with an incorrect value. If the
consumer decrements the counter exactly once before the producer runs again, the
counter value will be one more than it should be.
This case can result in an item being consumed more than once or an uninitialized item
being consumed. Alternatively, if the consumer loses the CPU in the middle of
decrementing the counter, the counter can end up with a value that is too small and a
produced item may be overwritten before it can be consumed.
An internal inconsistency occurs when the counter value does not agree with
the number of items inserted but not removed from the buffer. At this point the
program does not correctly represent the actions taken by the producer and the
consumer.
In this producer is like the push operation and consumer is just like the pop operation on
stack so for insert and deletion process synchronization is required.

(2)READERS AND WRITERS PROBLEM


There is a data area that is shared among a number of processes. Any
number of readers may simultaneously write to the data area. Only one
writer at a time may write to the data area.
If a writer is writing to the data area, no reader may read it.
If there is at least one reader reading the data area, no writer may write to
it. Readers only read and writers only write
A process that reads and writes to a data area must be considered a
writer (consider producer or consumer)

Readers/Writers problem models access to a database. It is acceptable to have


multiple processes reading the database at the same time, but if one process is
updating (writing) the database, no other processes may have access to the
database, no even readers.

Grow More Faculty of Degree Engineering Page 13


SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -
140702

Solution 1 use at your own risk

We demand of our solution that no reader be kept waiting unless a writer has
already obtained permission to use the resources; i.e. no reader should wait simply
because a writer is waiting for other readers to finish. It is possible that a writer
could wait indefinitly while a stream of readers arrived.

Solution 2 use at your own risk


We give priority to writers in which once a writer is ready to write, he performs his
"write" as soon as possible. Readers are allowed to wait indefinitely while a stream
of writers is working.

Solution 3 use at your own risk

When a reader arrives and a writer is waiting, the reader is suspended behind the
writer instead of being admitted immediately. In this way, a writer has to wait for
readers that were active when it arrived to finish but does not to wait for readers
that came along after it.
The readers-writers problem is commonly seen in database applications, where users are separated
into readers who never modify the database, and writers who read and modify the database. Although
we want only one writer at the same, using a single lock on the database would be overly restrictive,
since many readers can read at the same time.

Constraints

1. A reader should wait when a writer is accessing or waiting for the database (Condition
okToRead). (The writer has a higher priority over reader, since it is more difficult for a
writer to achieve exclusive access of the database.)

2. A writer should wait when there is a reader or a writer accessing the database (Condition
okToWrite).
3. A reader or a writer should wait when someone is modifying global states (Lock lock).

Basic Structure of the Solution

The following is the pseudocode for the readers-writers problem:


Grow More Faculty of Degree Engineering Page 14
SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -
140702

Reader
/ wait until no writers
/ access database
/ wake up waiting writers
Writer
/ wait until no readers or writers
/ access database
/ wake up waiting readers or writers

(3)DINING PHILOSHOPHER PROBLEM

The Dining Philosophers problem is a classic OS problem that’s usuallu stated


in very non-OS terms:

There are N philosphers sitting around a circular table eating spaghetti and
discussing philosphy. The problem is that each philosopher needs 2 forks to
eat, and there are only N forks, one
between each 2 philosophers. Design an algorithm that the philosophers can follow that
insures that none starves as long as each philosopher eventually stops eating, and such that
the maximum number of philosophers can eat at once.
Grow More Faculty of Degree Engineering Page 15
SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -
140702

Why describe problems this way? Well, the analogous situations in computers are
sometimes so technical that they obscure creative thought. Thinking about philosophers
makes it easier to think abstractly. And many of the early students of this field were
theoreticians who like abstract problems.There are a bunch of named problems - Dining
Philosophers, Drinking PhiliosophersHere’s an approach to the Dining Phils 1 that’s
simple and wrong:

void philosopher() {

while(1) {

sleep();

get_left_fork();

get_right_fork();

eat();

put_left_fork();

put_right_fork();

If every philosopher picks up the left fork at the same time, noone gets to eat
- ever.
Some other suboptimal alternatives:

• Pick up the left fork, if the right fork isn’t available for a given time, put the
left fork down,
wait and try again. (Big problem if all philosophers wait the same time - we get
the same failure mode as before, but repeated.) Even if each philosopher waits a
different random time, an

unlucky philosopher may starve (in the literal or technical sense).


Grow More Faculty of Degree Engineering Page 16
SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -
140702

• Require all philosophers to acquire a binary semaphore before picking up


any forks. This
guarantees that no philosopher starves (assuming that the semaphore is fair)
but limits parallelism dramatically.

MONITORS
A primary aim of an operating system is to share a computer installation among many
programs making unpredictable demands upon its resources. A primary tusk of its designer
is therefore to construct resource allocation (or scheduling) algorithms for resources of
various kinds (main store, drum store, magnetic tape handlers, consoles, etc.). In order to
simplify his task, he should try to construct separate schedulers for each class of resource.
Each scheduler will consist of a certain amount of local administrative data, together with
some procedures and functions which are called by programs wishing to acquire and release
resources. Such a collection of associated data and procedures is known as a monitor

Grow More Faculty of Degree Engineering Page 17


SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -
140702

SEMANTIC VIEW OF MONITOR


Grow More Faculty of Degree Engineering Page 18
SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -
140702

Monitor introduce the new name scope that shared data and the procedural that
are allow to access the data .we can say that monitors are 70% used to solve the
classical problem of an operating system.

CPU SCHEDULING ALGORITHM


CPU and I/O Burst Cycle

 The execution of a process consists of a cycle of CPU execution and I/O wait.
A process begins with a CPU burst, followed by an I/O burst, followed by
another CPU burst and so on. The last CPU burst will end will a system request to
terminate the execution.
 The CPU burst durations vary from process to process and computer to computer.
An I/O bound program has many very short CPU bursts.
A CPU bound program might have a few very long CPU bursts.
Grow More Faculty of Degree Engineering Page 19
SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -
140702

Histogram of CPU-burst Times


Grow More Faculty of Degree Engineering Page 20
SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -
140702

Types of Scheduling

 The key to the multiprogramming is scheduling. There are four types of scheduling that
an OS has to perform. These are:
o Long Term scheduling
The long term scheduling determines which programs are admitted to the system
for processing. Thus, it controls the level of multiprogramming.
Once admitted, a job or a user program becomes a process and is added to
the queue for the short term scheduling (in some cases added to a queue
for medium term scheduling).
Long term scheduling is performed when a new process is created.
The criteria used for long-term scheduling may include first-come-first
serve, priority, expected execution time, and I/O requirements.
o Medium-Term Scheduling
The medium-term scheduling is a part of swapping function. This is a
decision to add a process to those that are at least partially in main
memory and therefore available for execution.
The swapping-in decision is made on the need to manage the degree of
multiprogramming and the memory requirements of the swapped-out
process.
o Short-Term Scheduling
A decision of which ready process to execute next is made in short-term
scheduling.
o I/O Scheduling
The decision as to which process’s pending I/O requests shall be handled
by the available I/O device is made in I/O scheduling.

Grow More Faculty of Degree Engineering Page 21


SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -
140702

CPU Scheduler

 Whenever, the CPU becomes idle, the OS must select one of the processes in the ready-
queue to be executed.
 The selection process is carried out the short-term scheduler or CPU scheduler. The CPU scheduler
selects a process from the ready queue and allocates the CPU to that process.

 CPU scheduling decisions may take place when a process:


1. The running process changes from running to waiting state (current CPU burst of
that process is over).
2. The running process terminates
3. A waiting process becomes ready (new CPU burst of that process begins)
4. The current process switches from running to ready stat (e.g. because of timer
interrupt).

 Scheduling under 1 and 2 is nonpreemptive.


Once a process is in the running state, it will continue until it terminates or blocks
itself.
 Scheduling under 1 and 2 is preemptive.
Currently running process may be interrupted and moved to the Ready state by
OS.
Allows for better service since any one process cannot monopolize the processor
for very long
Grow More Faculty of Degree Engineering Page 22
SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -
140702

Dispatcher

 Dispatcher module gives control of the CPU to the process selected by the short-term
scheduler; this involves:
Switching context
Switching to user mode
Jumping to the proper location in the user program to restart that program
 Dispatch latency – time it takes for the dispatcher to stop one process and start another
running.

What is a Good Scheduler? Criteria

 User oriented
Turnaround time: time interval from submission of job until its completion. It includes
actual processing time plus time spent waiting for resources, including the processor. OR
the amount of time between moment a process first enters Ready State and the moment
the process exits Running State for the
last time (Completed).
Waiting time: sum of periods spent waiting in ready queue.
Response time: time interval from submission of job to first response.
Often a process can begin producing some output to the
Grow More Faculty of Degree Engineering
SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -
140702

user while continuing to process the request. Thus this is a better measure than
turnaround time from the user’s point of view.
Normalized turnaround time: ratio of turnaround time to service time.
Service Time: The amount of time process needs to be in running state (Acquired
CPU) before it is completed.
 System oriented
CPU utilization: percentage of time CPU is busy. CPU utilization may range
from 0 to 100%. In a real system, it should range from 40% to 90%.
Throughput: number of jobs completed per time unit. This depends on the
average length of the processes.
 Service time, wait time, turn around time, and throughput are some of the metrics used to
compare scheduling algorithms.
 Any good scheduler should:
Maximize CPU utilization and throughput
Minimize turnaround time, waiting time, response time

(1)FCFS Scheduling Algorithm(non-preemptive)

Process B.T. A.T. S.T. C.T. T.A.T. W.T.


ID
(C.T.- (T.A.T.-
A.T) B.T.)
P1 24 0 0 24 24 0
P2 3 0 24 27 27 24
P3 3 0 27 30 30 27

Grow More Faculty of Degree E ng ineering Page 24


SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -
140702

AVERAGE T.A.T:-24+27+30/3=27 ms
AVERAGE W.T.:-0+24+27/3=17 ms
(2)SJF (SHORTEST JOB FIRST) SCHEDULING(non-
preemptive)

Process B.T. A.T. S.T. C.T. T.A.T. W.T.


ID
(C.T.- (T.A.T.-
A.T) B.T.)
P1 6 0 3 9 9 3
P2 8 0 16 24 24 16
P3 7 0 9 16 16 9
P4 3 0 0 3 3 0
Average waiting time: (0+3+16+9)/4 = 7 ms
Average Turn Around Time :(9+24+16+3)/4:-13 ms
Grow More Faculty of Degree Engineering Page 25
SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -
140702

(3)SJF (Preemptive)

Process B.T. A.T. S.T. C.T. T.A.T. W.T.


ID
(C.T.- (T.A.T.-
A.T) B.T.)
P1 8 0 0 17 17 9
P2 4 1 1 5 4 0
P3 9 2 17 26 24 15
P4 5 3 5 10 7 2
Average Waiting time:-(9+0+15+2)/4=6.5 ms
Average Turn Around Time:-( 17+4+24+7)/4=13 ms
Grow More Faculty of Degree Engineering Page 26
SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -
140702

(4)Priority Scheduling(Non-Preemptive)

Process B.T. A.T. S.T. C.T. T.A.T. W.T.


ID
(C.T.- (T.A.T.-
A.T) B.T.)
P1 10 0 6 16 16 6
P2 1 0 0 1 1 0
P3 2 0 16 18 18 16
P4 1 0 18 19 19 18
P5 5 0 1 6 6 1
Average turn Around Time:-(16+1+18+19+6)/5=12ms
Grow More Faculty of Degree Engineering Page 27
SUBJECT NAME:-OPERATING SYSTEM SUBJECT CODE: -
140702

(6)Round Robin Scheduling Algorithm

Process B.T. A.T. S.T. C.T. T.A.T. W.T.


ID
(C.T.- (T.A.T.-
A.T) B.T.)
P1 24 0 0 30 30 6
P2 3 0 4 7 7 4
P3 3 0 7 10 10 7
Average Waiting time:-( 6+4+7)/3=5.66 ms
Average Turn Aroound Time :-( 30+7+10)/3=15.66 ms
Grow More Faculty of Degree Engineering Page 28

You might also like