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

OS Process Synchronization LECTURE

Uploaded by

ani1mesh2anand
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)
18 views

OS Process Synchronization LECTURE

Uploaded by

ani1mesh2anand
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/ 80

Chapter : Process Synchronization

Process Synchronization
 Background
 The Critical-Section Problem
 Peterson’s Solution
 Synchronization Hardware
 Semaphores
 Classic Problems of Synchronization
 Monitors
 Synchronization Examples
 Atomic Transactions
Background
 Co-Operating Process: that can affect or be affected by other
processes executing in system
 Concurrent access to shared data may result in data inconsistency
 Process Synchronization: Ensures coordination among processes and
maintains Data Consistency

 Process P1 Process P2
1. X=5
2. X=5+2
1. read(x);
2. x=x+5;

3. Printf( x);
Producer Consumer Problem
There can be two situations:

1. Producer Produces Items at Fastest Rate Than Consumer


Consumes

2. Producer Produces Items at Lowest Rate Than Consumer


Consumes
Producer Consumer Problem
Producer Produces Items at Fastest Rate Than
Consumer Consumes:

If Producer produces items at fastest rate than


Consumer consumes Then Some items will be
lost

Eg. Computer  Producer


Printer  Consumer
Producer Consumer Problem
Solution:
To avoid mismatch of items Produced or Consumed 
Take Buffer
Idea is: Instead of sending items from Producer to
Consumer directly Store items into buffer
Producer Consumer Problem
Buffer Can be:
1. Unbounderd Buffer:
1. No buffer size limit
2. Any no. of items can be stored
3. Producer can produce on any rate, there will always
be space in buffer

2. Bounderd Buffer:
1. Limited buffer size
Producer Consumer Problem
Bounderd Buffer:

If rate of Production > rate of Consumption:


Some items will be unconsumed in buffer

If rate of Production < rate of Consumption:


At some time buffer will be empty
Producer
while (true) {

/* produce an item and put in


nextProduced */

while (count == BUFFER_SIZE)


; // do nothing
buffer [in] = nextProduced;
in = (in + 1) % BUFFER_SIZE;
count++;
}
Consumer

while (true) {
while (count == 0) // buffer empty
{
; // do nothing
}
nextConsumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
count- -;

/* consume the item in nextConsumed


}
Race Condition
 When multiple processes access and manipulate the same data at the
same time, they may enter into a race condition.
 Race Condition: When output of the process is dependent on the
sequence of other processes.
 Race Condition occurs when processes share same data

 Process P1 Process P2
1. reads i=10
2. i=i+1 =11

1. P2 reads i=11 from memory


2. i=i+1 = 12
3. Stores i=11 in memory 3. Stores 12 in memory
Critical Section Problem
 Section of code or set of operations, in which process
may be changing shared variables, updating common
data.
 A process is in the critical section if it executes code
that manipulate shared data and resources.
 Each process should seek permission to enter its critical
section Entry Section
 Exit Section
 Remainder section: Contains remaining code
Structure of a process
Repeat
{
Locks are set here // Entry Section

Critical Section ( a section of code Critical Section


where processes work with shared
data)
// Exit Section
Locks are released here

Remainder Section
} until false.
Solution to: Critical Section
1. Mutual Exclusion:
It states that if one process is executing in its critical section, then
no other process can execute in its critical section.
2. Bounded Wait:
It states that if a process makes a request to enter its critical
section and before that request is granted, there is a limit on
number of times other processes are allowed to enter that
critical section.
Solution to: Critical Section
3. Progress:
It states that process cannot stop other process from entering
their critical sections, if it is not executing in its CS.
i.e. Decision of entry into Critical Section is made by
processes in Entry Section By Setting Lock in Entry
Section

Once process leaves C.S, Lock is released (i.e in Exit Section)


Solution to: Critical Section
3. Progress: Cont..
 N processes share same Critical Section

 Decision about which process can enter the Critical Section is


based on Processes which are interested to enter the C.S
(i.e. Processes of Entry Section)

 Processes that do not want to execute in CS should not take


part in decision
2 Process S/w Approaches/Solutions For
C.S
Consider 2 Process Syatem
 Algorithm 1.
Consider a Shared Variable, that can take 2 values: 1 or 2
a) if (shared variable == 1)
P1 can enter to Critical Section

b) if (shared variable == 2)
P2 can enter to Critical Section
2 Process S/w Approaches For C.S
 Let shared variable is turn i.e. turn : 1 or 2
(Let i=1 and j=2)
Pi:
while (turn != i)
{ do skip; } // P2 is executing

P1 is in Critical Section;
turn=j; // turn=2;

Thus Mutual Exclusion is Satisfied


2 Process S/w Approaches For C.S
 Progress
Now, Turn =2 i.e. process P2 can enter C.S.
But
Suppose P2 does not want to enter C.S.
So.. turn =1 is never set

Progress is not satisfied.


2 Process S/W Approach/Solution
Algorithm 2:
Algorithm 1 does not focus on state of process just
consider which process is in critical section.

Sol: Replace variable “turn” with an array containing


2 values(True and False)
boolean flag[2].
i.e. use flags
Elements of the array are initialized to false
Algorithm 2
do{
flag[i] = true; //Pi is ready to enter C.S
while (flag[j]); //Pi checks for Pj whether Pj is ready to
enter to C.S or not
Critical Section //Pi enters to C.S
flag[ i ]= false; Pi allows other processes to enter the C.S
Remainder Section
} while (1);
Algorithm 3: Peterson’s Solution
 It is a Two process solution
 The two processes share two variables:
 int turn;
 Boolean flag[2]

 The variable turn indicates whose turn it is to enter the critical


section.

 The flag array is used to indicate if a process is ready to enter


the critical section.
 flag[i] = true implies that process Pi is ready!
Algorithm for Process Pi

do {
flag[ i ] =true; // Pi is ready to enter C.S
turn=j;
while(flag[j] && turn ==j); // (flag and turn of Pj is True, Until
this condition is true, Pi can not enter C.S)
CRITICAL SECTION
flag[i]=false;
REMAINDER SECTION
}while(1);
Synchronization Hardware
Hardware Solution to C.S.
 Many systems provide hardware support for critical section code

 Uni-processors – could disable interrupts


 Currently running code would execute without preemption

 Modern machines provide special atomic hardware instructions


 Atomic = non-interruptable
 Either test memory word and set value
 Or swap contents of two memory words
Hardware Solution to C.S.
1. Interrupt Disabling

1. Process leaves control of CPU when it is


interrupted.
2. Solution is:
1. To have each process disable all interrupts just
after entering to the critical section.
2. Re-enable interrupts after leaving critical section
Hardware Solution to C.S.

 Interrupt Disabling

Repeat

Disable interrupts

C.S

Enable interrupts

Remainder section
Hardware Solution to C.S.
2. Hardware instructions
1. Machines provide instructions that can read, modify
and store memory word
2. Common inst. are:
1. Test and Set
This inst. Provides action of testing a variable and set
its value

It executes atomically
Test and Set instructions operates on single Boolean
variable.
Hardware Solution to C.S.
//initially lock is
FALSE
Swap Instruction

 Definition:

void Swap (boolean a, boolean b)


{
boolean temp = a;
a = b;
b = temp:
}
Hardware Solution to C.S. Using
Swap
Shared data : lock initialized to false
Boolean:lock; swap(lock,flag)
{
do{ temp = lock;
flag=true; lock=flag;
while(flag) flag=temp;
swap(lock,flag);
C.S. }
lock=false;
Remainder Section
} While(True);
Semaphore

 Synchronization tool that maintains concurrency using variables


 Semaphore S is a integer variable which can take positive values
including 0. It is accessed from 2 operations only.
Operations On Semaphore:
 wait() and signal()

1. Wait Operation is also known as P() which means to test


2. Signal Operation is also known as V() which means to increment

 Entry to C.S. is controlled by wait()


 Exit from C.S. is signaled by signal()
Semaphore
 Can only be accessed via two
indivisible (atomic) operations and
S=1
 For critical Section problem
semaphore value is always 1
 P(S) and V(S):
wait (S) {
while (S <= 0)
do skip ; // no-op}
S- -;
C.S
signal (S) {
S++; }
Semaphore as General Synchronization Tool

Types of Semaphores:
 Counting semaphore – when integer value can be
any non-negative value
 Binary semaphore – integer value can range only
between 0 and 1
 Also known as mutex locks
Semaphore and Busy Waiting
Disadvantage of Semaphore: Busy Waiting

 When a process is in C.S. and any other process that wants to


enter C.S. loops continuously in entry section.

 Wastes CPU cycles

 Semaphore that implements busy waiting is known as: Spin


Lock
Semaphore Implementation with no Busy
waiting
 With each semaphore there is an associated waiting queue.
Each entry in a waiting queue has two data items:

 value (of type integer)


 pointer to next record in the list
Semaphore Implementation with no Busy
waiting
Instead of waiting, a process blocks itself.

 Two operations:
 block – place the process invoking the operation on the
waiting queue.
 wakeup – remove one of processes in the waiting queue and
place it in the ready queue.
Semaphore Implementation with no Busy
waiting
 Implementation of wait:
S=1
wait (S){
value--;
if (value < 0) {
add process P to waiting queue
block();
}
C.S
}
Semaphore Implementation with no Busy
waiting

 Implementation of signal:

Signal (S){
value++; //“value” has -ve value i.e -1 here
if (value <= 0) {
remove a process P from the waiting queue
wakeup(P); }
}
Deadlock and Starvation

 Deadlock – two or more processes are waiting


indefinitely for an event that can be caused by
only one of the waiting processes

 Starvation – indefinite blocking. A process may


never be removed from the semaphore queue in
which it is suspended.
Classical Problems of Synchronization
 Bounded-Buffer Problem
 Readers and Writers Problem
 Dining-Philosophers Problem
Bounded-Buffer Problem

 N buffers, each can hold one item


 Semaphore mutex initialized to the value 1
 Semaphore full initialized to the value 0
 Semaphore empty initialized to the value N.

 mutex= 1
 full= 0
 empty= N
Bounded Buffer Problem (Cont.)

 The structure of the producer process


while (true) {

// produce an item

wait (empty);
wait (mutex);

// add the item to the buffer

signal (mutex);
signal (full);
}
Bounded Buffer Problem (Cont.)

 The structure of the consumer process

while (true) {
wait (full);
wait (mutex); // mutex=1

// remove an item from buffer

signal (mutex); // mutex=0


signal (empty);

// consume the removed item


}
Readers-Writers Problem

 A data set is shared among a number of concurrent


processes
 Readers – only read the data set; they do not perform
any updates
 Writers – can both read and write.

 Problem – allow multiple readers to read at the same time.


Only one single writer can access the shared data at the
same time.

 Shared Data
 Data set
 For Readers: Semaphore mutex initialized to 1.
 For Writers: Semaphore wrt initialized to 1.
 Integer readcount initialized to 0.
Readers-Writers Problem (Cont.)

 The structure of a writer process

while (true) {
wait (wrt) ;

// writing is performed

signal (wrt) ;
}
Readers-Writers Problem (Cont.)
 The structure of a reader process
while (true) {
wait (mutex) ;
readcount ++ ;
if (readcount == 1)
wait (wrt) ; //( don’t allow writers)
signal (mutex); //(allow other readers to come)

// reading is performed

wait (mutex) ; // (one by one readers leave the C.S.)


readcount - - ;
if (readcount == 0)
{ signal (wrt) ; } // last reader will do this
signal (mutex) ; // mutex=1 (for readers to exit and writer to
come)
}
Dining-Philosophers Problem

 Shared data
 Bowl of rice (data set)
 Semaphore chopstick [5] initialized to 1
Dining-Philosophers Problem (Cont.)

 The structure of Philosopher i:

While (true) {
wait ( chopstick[i] );
wait ( chopstick[ (i + 1) % 5] ); // =1

// eat

signal ( chopstick[i] );
signal (chopstick[ (i + 1) % 5] );

// think

}
Problems with Semaphores

 Incorrect use of semaphore operations:

 signal (mutex) …. wait (mutex)

 wait (mutex) … wait (mutex)

 Omitting of wait (mutex) or signal (mutex) (or both)


Monitors
 A way to encapsulate the Critical Section by making class around the critical
section and allowing only one process to be active in that class at one time.
 Only one process may be active within the monitor at a time
 Name of Monitor
 Initialization Code Section
 Procedure to request the Critical Data
 Procedure to release the Critical Data

monitor monitor-name
{
// shared variable declarations
procedure P1 (…) { …. }

procedure Pn (…) {……}
Initialization code ( ….) { … }

}
}
Monitors
Schematic view of a Monitor

Only one process at a time can be in monitor


Condition Variables
Condition Variables
 condition x, y;
 Two operations on a condition variable:

 x.wait () – a process that invokes the operation is suspended until


x.signal()

 x.signal () – resumes one of processes (if any) that invoked x.wait ()


There could be different conditions for which a process could be waiting

Let a process made the request to C.S. but no critical data is available, So
we would not go back to check all the conditions again to run the request,
As we have checked some conditions so processes will be lined up for
excess to C.S.
Monitor with Condition Variables
Solution to Dining Philosophers (cont)
 Each philosopher ‘ i ’ invokes the operations pickup() and putdown() in
the following sequence:

dp.pickup (i)

EAT

dp.putdown (i)
Solution to Dining Philosophers
monitor DP
{
enum { THINKING; HUNGRY, EATING) state [5] ;
condition self [5];

void pickup (int i) {


state[i] = HUNGRY;
test(i);
if (state[i] != EATING)
self [i].wait;
}
void putdown (int i) {
state[i] = THINKING;
// test left and right neighbors
test((i + 4) % 5);
test((i + 1) % 5);
}
Solution to Dining Philosophers (cont)

void test (int i) {


if ( (state[(i + 4) % 5] != EATING) && (state[i] == HUNGRY) &&
(state[(i + 1) % 5] != EATING) )
{
state[i] = EATING ;
self[i].signal() ;
}
}

initialization_code() {
for (int i = 1; i <= 5; i++)
state[i] = THINKING;
}
}
MCQ Questions
Which process can be affected by other
processes executing in the system?
a) cooperating process
b) child process
c) parent process
d) init process
MCQ Questions
1a
MCQ Questions
When several processes access the same
data concurrently and the outcome of
the execution depends on the particular
order in which the access takes place,
is called
a) dynamic condition
b) race condition
c) essential condition
d) critical condition
MCQ Questions
2b
MCQ Questions
If a process is executing in its critical
section, then no other processes can
be executing in their critical section.
This condition is called
a) mutual exclusion
b) critical exclusion
c) synchronous exclusion
d) asynchronous exclusion
MCQ Questions
3a
MCQ Questions
Which one of the following is a
synchronization tool?
a) thread
b) pipe
c) semaphore
d) socket
MCQ Questions
4c
MCQ Questions
A semaphore is a shared integer variable
a) that can not drop below zero
b) that can not be more than zero
c) that can not drop below one
d) that can not be more than one
MCQ Questions
5a
MCQ Questions
Mutual exclusion can be provided by the
a) mutex locks
b) binary semaphores
c) both mutex locks and binary
semaphores
d) none of the mentioned
MCQ Questions
6c

Explanation: Binary Semaphores are


known as mutex locks.
MCQ Questions
When high priority task is indirectly
preempted by medium priority task
effectively inverting the relative priority
of the two tasks, the scenario is called
a) priority inversion
b) priority removal
c) priority exchange
d) priority modification
MCQ Questions
7a
MCQ Questions
8. Process synchronization can be done
on
a) hardware level
b) software level
c) both hardware and software level
d) none of the mentioned
MCQ Questions
8c
MCQ Questions
9. A monitor is a module that encapsulates
a) shared data structures
b) procedures that operate on shared data
structure
c) synchronization between concurrent
procedure invocation
d) all of the mentioned
MCQ Questions
9d
MCQ Questions
To enable a process to wait within the
monitor,
a) a condition variable must be declared
as condition
b) condition variables must be used as
boolean objects
c) semaphore must be used
d) all of the mentioned
MCQ Questions
10 a
End of Chapter

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy