Process and Synchronization (Problems: Race Condition and Deadlock)

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 36

Process And Synchronization

(Problems : Race Condition and


Deadlock)
Reference : Operating System Concepts by Galvin, Operating
System Design and Implementation by Tanenbaum, Sistem
Operasi by Kelompok Gotong Royong
Interprocess Communication :
Basic Concept
• Synchronization : To avoid data inconsistency
because of concurrent data access.
• 3 issues of IPC :
• How one process can pass information to
another
• Making sure processes don’t get each other way
in critical activities
• Proper sequencing when dependencies are
present
Problem : Race Condition
two or more processes are reading or writing
some shared data and the final result depends
on who runs precisely.
Example : Producer Consumer Problem
#define bufferSize 100
Int counter = 0

Void producer (void) {


int item;
while (1) {
item = produce_item();
if (counter == bufferSize) sleep();
insert_item(item);
counter++;
if (counter == 1 ) wakeup (consumer) ;
}
}

Void consumer (void) {


int item;
while (1) {
if (counter == 0) sleep ();
item = remove_item();
counter--;
if (counter == bufferSize-1) wakeup(producer) ;
consume_item (item);
}
}
Problem : the access to counter is unconstrained
Example :
• The consumer has just read the variable counter, noticed it's zero and is
just about to move inside the if block.
• Just before calling sleep, the consumer is interrupted and the producer is
resumed.
• The producer creates an item, puts it into the buffer, and increases
counter.
• Because the buffer was empty prior to the last addition, the producer
tries to wake up the consumer.
• Unfortunately the consumer wasn't yet sleeping, and the wakeup call is
lost. When the consumer resumes, it goes to sleep and will never be
awakened again. This is because the consumer is only awakened by the
producer when counter is equal to 1.
• The producer will loop until the buffer is full, after which it will also go to
sleep.
Other Example : Producer Consumer Problem
Problem : (counter = 2)
//counter++ 1.producer: register1 = counter
register1 = counter (register1 = 2)
2.producer: register1 =
register1 = register1 + 1
register1 + 1 (register1 = 3)
counter = register1 3.consumer: register2 =
//counter— counter (register2 = 2)
register2 = counter 4.Consumer: register2 =
register2 - 1 (register2 = 1)
register2 = register2 - 1
5.consumer: counter =
counter = register2 register2 (counter = 1)
6.producer: counter = register1
(counter = 3)
Critical Sections / Critical Regions
part of the program where the shared memory is accessed by process
To avoid race condition : arrange matters such that no two processes were ever in their
critical regions at the same time

The solution must have these conditions:


1. Mutual exclusion – only one process allowed to access critical section.
2. Progress - a process operating outside of its critical section cannot prevent other
processes from entering theirs; processes attempting to enter their critical sections
simultaneously must decide which process enters eventually.
3. Bounded waiting - a process attempting to enter its critical region will be able to do so
eventually.
Solution : Algorithm I
P0 P1 Problem :
turn = 0 ; turn = 1 ; When one of the
do { do { processes don’t use
its turn to access
while(turn!=0) { while(turn!=1) {
critical section
//P1 turn //P0 turn
} }
critical section critical section
turn = 1; turn = 0;
}while (1) }while (1)
Solution : Algorithm II
P0 P1 Inizialization :
do { do { Both flag set to false, if
flag[0]=true; flag[1]=true; any of them want to
use critical section
while (flag[1]) { while (flag[0]) {
then set flag true
//P1 //P0
Problem :
} }
When both of them
critical section critical section want to access
flag[0]=false; flag[1]=false; critical section
}while (1) }while (1)
Solution : Algorithm III (Peterson’s
Algorithm)
P0 P1 Solve the problem
do { do { from the previous
flag[0]=true; flag[1]=true; algorithm
turn = 1; turn = 0;
while ((flag[1])&&
while ((flag[0])&&
turn==1))
turn==0))
{
{
//P1&P1 turn
//P0&P0 turn
}
critical section
}
flag[0]=false; critical section
}while (1) flag[1]=false;
}while (1)
The Deadlock Problem
A set of blocked processes each holding a
resource and waiting to acquire a resource held
by another process in the set.

Example
System has 2 CD drives. P1 and
P2 each hold one CD drive
and each needs the other
one.
Definitions
A process is deadlocked if it is waiting for an event
that will never occur.
Typically, more than one process will be involved in a
deadlock
A process is indefinitely postponed if it is delayed
repeatedly over a long period of time while the
attention of the system is given to other
processes,
i.e. the process is ready to proceed but never gets
the CPU
a specific condition when
two or more processes
are each waiting for the
other to release a
resource, or more than
two processes are waiting
for resources in a circular
chain
Resources
Resource
commodity required by a process to execute
Resources can be of several types
Serially Reusable Resources
CPU cycles, memory space, I/O devices, files
acquire -> use -> release
Consumable Resources
Produced by a process, needed by a process - e.g.
Messages, buffers of information, interrupts
create ->acquire ->use
Resource ceases to exist after it has been used
System Model
Resource types
R1, R2,….Rm
Each resource type Ri has Wi instances
Assume serially reusable resources
request -> use -> release
Conditions for Deadlock
The following 4 conditions are necessary and sufficient for
deadlock
Mutual Exclusion:
Only once process at a time can use the resource.
Hold and Wait:
Processes hold resources already allocated to
them while waiting for other resources.
No preemption:
Resources are released by processes holding them
only after that process has completed its task.
Circular wait:
A circular chain of processes exists in which each
process waits for one or more resources held by
the next process in the chain.
Resource Allocation Graph
A set of vertices V and a set of edges E
V is partitioned into 2 types
P = {P1, P2,…,Pn} - the set of processes in the
system
R = {R1, R2,…,Rn} - the set of resource types in
the system
Two kinds of edges
Request edge - Directed edge Pi ---> Rj
Assignment edge - Directed edge Rj ----> Pi
Resource Allocation Graph
Process

Resource type with 4 instances

Pi requests instance of Rj

Pi is holding an instance of Rj
Graph with no cycles
R1 R2

P1 P2 P3

R3 R4
Graph with cycles

R1 P2

P1 P3

R2 P4
Graph with cycles and deadlock
R1 R2

P1 P2 P3

R3 R4
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.
Methods for handling deadlocks
1. Ignore the problem and pretend that
deadlocks never occur in the system;
Used by many operating systems, e.g. UNIX
2. Detection and Recovery
3. Avoidance
4. Prevention
Ignore The Problem
• Ostrich Algorithm
• a strategy of ignoring potential problems on the
basis that they may be exceedingly rare - "to stick
your head in the sand and pretend that there is
no problem". This assumes that it is more cost-
effective to allow the problem to occur than to
attempt its prevention.
Deadlock Detection
• Identify the processes and resources that
have been deadlocked.
• Track the request and release of the
resources.
Recovery from Deadlock: 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?
Priority of the process
How long the process has computed, and how
much longer to completion.
Resources the process has used.
Resources process needs to complete.
How many processes will need to be terminated.
Is process interactive or batch?
Recovery from Deadlock: Resource
Preemption
Selecting a victim - minimize cost.
Rollback
return to some safe state, restart process from
that state.
Starvation
same process may always be picked as victim;
include number of rollback in cost factor.
Deadlock Avoidance
Only allow access to the resource request that doesn’t
led to deadlock
Requires that the system has some additional information
available.
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.
Deadlock Avoidance (Bankir’s
Algorithm)

 Set of resources, set of customers, banker


 Rules
 Each customer tells banker maximum number of resources
it needs.
 Customer borrows resources from banker.
 Customer returns resources to banker.
 Customer eventually pays back loan.

 Banker only lends resources if the system


will be in a safe state after the loan.
Safe state
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 safe sequence of all processes
and can satisfy all the request
Unsafe State
• System is in unsafe state if there no exists a
safe sequence of all processes and can’t
satisfy all the request
Example

• Max system resources : 10


• There are 3 processes : A, B, C
• A needs max resources : 10, now is holding : 2
• B needs max resources : 3 , now is holding : 1
• C needs max resources : 7 , now is holding : 3
• Available resources : 4
PROCESS ALLOCATED MAX
RESOURCES RESOURCES
A 2 10
B 1 3
C 3 7
FREE : 4

SAFE STATE = ?
UNSAFE STATE = ?
If a system is in a safe state  no deadlocks.
If a system is in unsafe state  possibility of
deadlock.
Avoidance  ensure that a system will never
reach an unsafe state.
Deadlock Prevention
If any one of the conditions for deadlock (with reusable
resources) is denied, deadlock is impossible.
Restrain ways in which requests can be made
Mutual Exclusion
non-issue for sharable resources
cannot deny this for non-sharable resources (important)
Hold and Wait - guarantee that when a process
requests a resource, it does not hold other
resources.
Force each process to acquire all the required resources
at once. Process cannot proceed until all resources
have been acquired.
Low resource utilization, starvation possible
Deadlock Prevention (cont.)
No Preemption
If a process that is holding some resources requests
another resource that cannot be immediately
allocated to it, the process releases the resources
currently being held.
Preempted resources are added to the list of resources
for which the process is waiting.
Process will be restarted only when it can regain its old
resources as well as the new ones that it is requesting.
Circular Wait
Impose a total ordering of all resource types.
Require that processes request resources in increasing
order of enumeration; if a resource of type N is held,
process can only request resources of types > N.

You might also like