OS Session2 U2
OS Session2 U2
Dr P S Patheja
– wait(S) = test or Proberen(S), acquire, P(S)
– signal(S) = set or Verhogen(S), release, V(S)
• Do these operations atomically
Semaphores (2)
Semaphore S is an integer variable can be modified by:
• initialization OR
• By two atomic operations: Wait and Signal.
Classical definition of Wait and Signal are:
Wait (S): decrements value of S as soon as it would become non
negative (positive). Completion of wait operation, once the decision is
made to decrement its argument Semaphore, must be indivisible.
Signal (S): increments the value of its argument Semaphore, S, as
an indivisible operation.
Indivisible Operation means when One process modifies the
Semaphore Value, S, NO other process can Simultaneously modify the
same Semaphore Value.
wait (S):
Dr P S Patheja
while (S <= 0) do no-op;
[Keep Testing]
S=S–1;
signal (S):
S=S+1;
Critical Section of n Processes
• Shared data:
semaphore mutex; // initiallized to 1
• Process Pi:
do {
wait(mutex);
critical section
signal(mutex);
Dr P S Patheja
remainder section
} while (TRUE);
PROCESS SYNCHRONIZATION
Semaphores
Semaphores can be used to force synchronization
( precedence ) if the preceeder does a signal at the
end, and the follower does wait at beginning.
For example, here we want S1 to execute before S2.
P1: P2:
statement 1; wait ( synch );
Dr P S Patheja
signal ( synch ); statement 2;
4
Implementation of Semaphores
We don't want to loop on busy, so will suspend instead:
• Block on semaphore == False,
• Wakeup on signal (semaphore becomes True),
• There may be numerous processes waiting for the
semaphore, so keep a list of blocked processes,
• Wakeup one of the blocked processes upon getting a
signal ( choice of who depends on strategy ).
To PREVENT looping, we redefine the semaphore structure as record:
Type semaphore = record
{ int value;
L : *list of process; /* linked list of PTBL waiting on S */
}
Process is added to “List of process” when WAIT op. occurs &
Process is removed from “List of process” when SIGNAL op. occurs.
8
Implementation of Semaphores
typedef struct {
int value;
struct process *list; /* linked list of PTBL waiting on S */
} SEMAPHORE;
SEMAPHORE s; SEMAPHORE s;
wait(s) { signal(s) {
s.value = s.value - 1; s.value = s.value + 1;
if ( s.value < 0 ) { if ( s.value <= 0 ) {
add this process to s.L; remove a process P from s.L;
block; wakeup(P);
} }
} }
Block and Wakeup are SYSTEM CALLS provided by OS.
Dr P S Patheja
• It's critical that these be atomic - in uniprocessors we can disable interrupts,
but in multiprocessors other mechanisms for atomicity are needed.
• Popular incarnations of semaphores are as "event counts" and "lock
managers”.
9
Two Types of Semaphores
1. Counting semaphore – integer value can range
over an unrestricted domain.
2. Binary semaphore – integer value can range
only between 0 and 1 (really a Boolean);
can be simpler to implement (use waitB and
signalB operations); same as Mutex lock.
Dr P S Patheja
using 2 binary semaphores (that protect its
counter).
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
• Let S and Q be two semaphores initialized to 1
P0 P1
wait (S); wait (Q);
wait (Q); wait (S);
. .
. .
. .
signal (S); signal (Q);
Dr P S Patheja
signal (Q); signal (S);
• Starvation – indefinite blocking. A process may
never be removed from the semaphore queue
in which it is suspended.
Problems with Semaphores
• Semaphores provide a powerful tool for enforcing
mutual exclusion and coordinate processes.
• But wait(S) and signal(S) are scattered among several
processes. Hence, difficult to understand their
effects.
• Usage must be correct in all the processes (correct
order, correct variables, no omissions).
• Incorrect use of semaphore operations:
– signal (mutex) …. wait (mutex)
Dr P S Patheja
– wait (mutex) … wait (mutex)
– Omitting of wait (mutex) or signal (mutex) (or both)
• One bad (or malicious) process can fail the entire
collection of processes.
Dr P S Patheja
Classical Problems of Synchronization
• Bounded-Buffer Problem
• Readers and Writers Problem
• Dining-Philosophers Problem
Dr P S Patheja
Bounded-Buffer Problem
• N buffers, each can hold one item
• We Need 3 Semaphores:
• Semaphore mutex initialized to the value 1
• Semaphore full initialized to the value 0
• Semaphore empty initialized to the value N.
Dr P S Patheja
Shared data: semaphore full, empty, mutex;
Initially: full = 0, empty = n, mutex = 1
THE BOUNDED BUFFER ( PRODUCER / CONSUMER ) PROBLEM:
producer:
do { Structure of
produce an item in nextp Producer Process
wait (empty); /* Buffer = Full if
empty = 0*/
wait (mutex); /* Buffer guard*/
add nextp to buffer
signal (mutex);
signal (full);
} while(TRUE);
Dr P S Patheja
22
THE BOUNDED BUFFER ( PRODUCER / CONSUMER ) PROBLEM:
producer:
do { Structure of
produce an item in nextp Producer Process
wait (empty); /* Buffer = Full if
empty = 0*/
wait (mutex); /* Buffer guard*/
add nextp to buffer
signal (mutex);
signal (full);
} while(TRUE);
consumer:
do {
Dr P S Patheja
wait (full); /* Buffer = Empty If Full = 0*/
wait (mutex);
remove an item from buffer to nextc
signal (mutex);
Structure of signal (empty);
Consumer Process consume an item in nextc
} while(TRUE);
23
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
Dr P S Patheja
– Data set
– Semaphore mutex initialized to 1.
– Semaphore wrt initialized to 1.
– Integer readcount initialized to 0.
Readers-Writers with active readers
Dr P S Patheja
Readers-Writers with an active writer
Dr P S Patheja
THE READERS/WRITERS PROBLEM:
BINARY_SEMAPHORE wrt = 1;
BINARY_SEMAPHORE mutex = 1; Writer:
Int readcount = 0; do {
wait( wrt );
/* writing is performed */
signal( wrt );
} while(TRUE);
Reader:
do {
wait( mutex ); /* 1st reader wants to entry*/
readcount = readcount + 1;
if readcount == 1 then wait(wrt ); /* 1st reader locks writer */
signal( mutex ); WAIT ( S ):
while ( S <= 0 );
/* reading is performed */ S = S - 1;
Dr P S Patheja
wait( mutex ); SIGNAL ( S ):
S = S + 1;
readcount = readcount - 1;
if readcount == 0 then signal(wrt ); /*last reader frees writer */
signal( mutex );
} while(TRUE);
29
Dining Philosophers Problem (1)
1. Philosophers spend their lives
alternating between thinking and
eating.
2. Five philosophers can be seated
around a circular table.
3. There is a shared bowl of rice.
4. In front of each one is a plate.
5. Between each pair of philosophers
there is a chopstick, so there are
five chopsticks.
Dr P S Patheja
6. It takes two chopsticks to take/eat
rice, so while n is eating neither n+1
nor n-1 can be eating.
Dining Philosophers Problem (2)
• Each one thinks for a while,
gets the chopsticks/forks needed,
eats, and
puts the chopsticks/forks down again, in an
endless cycle.
• Illustrates the difficulty of allocating resources
among process without deadlock and starvation.
Dr P S Patheja
Dining Philosophers Problem (3)
• The challenge is to grant requests for chopsticks
while avoiding deadlock and starvation.
• Deadlock can occur if everyone tries to get their
chopsticks at once. Each gets a left chopstick,
and is stuck, because each right chopstick is
someone else’s left chopstick.
Dr P S Patheja
Dining-Philosophers Problem (Cont.)
• The structure of Philosopher i:
While (true) {
wait ( chopstick[i] );
wait ( chopStick[ (i + 1) % 5] );
// eat
signal ( chopstick[i] );
signal (chopstick[ (i + 1) % 5] );
Dr P S Patheja
// think
} This solution is perfect if NO
neighbour is eating simultaneously.
THE DINING PHILOSOPHERS PROBLEM:
• 5 philosophers with 5 chopsticks sit around a circular table.
• Suppose all 5 philosopher become hungry simultaneously AND Each
grab their left (or right) chopstick then
• All element of chopstick will now become to Zero and
• When philosopher try to grab chopstick of other hand, It will be
Delayed for Ever.
Clearly deadlock is rampant ( and starvation possible.)
Several solutions are possible:
1. Allow only 4 philosophers to be hungry at a time (4 to sit
simultaneously).
2. Allow pickup only if both chopsticks are available. (Done
Dr P S Patheja
in critical section )
3. Odd # philosopher always picks up left chopstick 1st,
even # philosopher always picks up right chopstick 1st.
Prevents Deadlock BUT possibility of Starvation exists.
37
Dr P S Patheja