ProcessProcess
SynchronizationSynchronization
Mr. SUBHASIS DASH
SCHOLE OF COMPUTER ENGINEERING.
KIIT UNIVERSITY
BHUBANESWAR
Cooperating ProcessesCooperating Processes
Independent process cannot affect or be affected
by the execution of another process
Cooperating process can affect or be affected by
the execution of another process
Advantages of process cooperation
Information sharing
Computation speed-up
Modularity
Convenience
Producer-Consumer ProblemProducer-Consumer Problem
Paradigm for cooperating processes,
producer process produces information
that is consumed by a consumer
process
unbounded-buffer places no practical limit
on the size of the buffer
bounded-buffer assumes that there is a
fixed buffer size
Bounded-Buffer – Shared-Memory SolutionBounded-Buffer – Shared-Memory Solution
Shared data
#define BUFFER_SIZE n
typedef struct {
. . .
} item;
item buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
Solution is correct, but can only use
BUFFER_SIZE is [n-1] elements.
( ( ( in = ( in + 1 ) % BUFFER SIZE count) ==
out) :- buffer full
(in == out) :- buffer empty
BackgroundBackground
Concurrent access to shared data may result in data
inconsistency
Maintaining data consistency requires mechanisms to ensure
the orderly execution of cooperating processes
Suppose that we wanted to provide a solution to the consumer-
producer problem that fills all the buffers. We can do so by
having an integer count that keeps track of the number of full
buffers. Initially, count is set to 0. It is incremented by the
producer after it produces a new buffer and is decremented by
the consumer after it consumes a buffer.
ProducerProducer
while (true) {
/* produce an item and put in nextProduced */
while (count == BUFFER_SIZE)
; // do nothing
buffer [in] = nextProduced;
in = (in + 1) % BUFFER_SIZE;
count++;
}
ConsumerConsumer
while (true) {
while (count == 0)
; // do nothing
nextConsumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
count--;
/* consume the item in nextConsumed
}
Producer & Consumer CodeProducer & Consumer Code
while (true)
{
/* produce an item and put in next
Produced */
while (count == BUFFER_SIZE);
// do nothing
buffer [in] = nextProduced;
in = (in + 1) % BUFFER_SIZE;
count++;
}
while (true)
{
while (count == 0);
// do nothing
nextConsumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
count--;
/* consume the item in next
Consumed */
}
Race ConditionRace Condition
count++ could be implemented as
register1 = count
register1 = register1 + 1
count = register1
count-- could be implemented as
register2 = count
register2 = register2 - 1
count = register2
Consider this execution interleaving with “count = 5” initially:
S0: producer execute register1 = count {register1 = 5}
S1: producer execute register1 = register1 + 1 {register1 = 6}
S2: consumer execute register2 = count {register2 = 5}
S3: consumer execute register2 = register2 - 1 {register2 = 4}
S4: producer execute count = register1 {count = 6 }
S5: consumer execute count = register2 {count = 4}
CRITICAL SECTION (CS) PROBLEMCRITICAL SECTION (CS) PROBLEM
Critical is a segment of code in each process where process wants
to change there common variable.
But CS allows only one process to execute in its CS –: MUTUALLYMUTUALLY
EXCLUSIVEEXCLUSIVE.
There are 3 different sections:-
ENTRY SECTION
EXIT SECTION
REMINDER SECTION
Example:-
repeat
ENTRY
critical section
EXIT
reminder section
until false
Solution to Critical-Section ProblemSolution to 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 only those process that are not executing their reminder
section can participate in the selection of the processes that
which will enter the critical section next, and this selection cann’t
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
11stst
S/W Solution for CS problemS/W Solution for CS problem
PI’s Algorithm
repeat
var turn = i
While ( turn != “ i ”) do no-op;
Critical section
turn=“ j ”;
until false
PJ’s Algorithm
repeat
var turn = j
While ( turn != “ j ”) do no-op;
Critical section
turn=“ i ”;
until false
22ndnd
SolutionSolution
PI’s Algorithm
Var flag : array [ i…j] of boolen
repeat
flag [i] = true;
While ( flag [j] == “ true ”) do no-op;
Critical section
Flag [i]=“ false ”;
until false
PJ’s Algorithm
Var flag : array [ i…j] of boolen
repeat
flag [ j ] = true;
While ( flag [ i ] == “ true ”) do no-op;
Critical section
Flag [j]=“ false ”;
until false
Peterson’s Two Process SolutionPeterson’s Two Process Solution
Two process solution
Assume that the LOAD and STORE instructions are atomic;
that is, cannot be interrupted.
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!
Peterson’s SolutionPeterson’s Solution
PI’s Algorithm
repeat
S1: flag [ i ] = TRUE;
S2: turn = j;
S3: while ( flag[ j ] == TRUE &&
turn != i ) do no-op;
CRITICAL SECTION
flag [ i ] = FALSE;
until false
PJ’s Algorithm
repeat
L1: flag [ j ] = TRUE;
L2: turn = i;
L3: while ( flag [ i ] == TRUE &&
turn != j) do no-op;
CRITICAL SECTION
flag [ j ] = FALSE;
until false
Sequence of execution:
S1; S2; L1;L2; S1;L1;L2;S2; L1;S1;L2;S2
The Bakery Algorithm (N process Solution)The Bakery Algorithm (N process Solution)
Generalization for n processes (Customers).
Each process has an ID (Customers IDs are in order).
Before entering its critical section,
A process receives a number (in order).
Process holds smallest number enters in to its critical
section first.
Drawback Can not guarantee that two processes
(Customers) do not receive the same number (Tie).
Tie breaker is done using the process id (Custer with
lower customer ID is served first)
if processes i and j hold the same number and i < j then i enters
first.
The Bakery Algorithm (N process Solution)The Bakery Algorithm (N process Solution)
Data Structure Common
Variable  choosing[0…..n-1] of boolean
 number[0….n-1] of integer
Initially  choosing [i] = false
 number [i] = 0
Notation  ( a, b ) < ( c, d ) if a < c or if a = c & b < d
Number
ID
Number
ID
The Bakery Algorithm (N process Solution)The Bakery Algorithm (N process Solution)
Repeat
choosing[ i ] := true;
number[ i ] :=max ( number[0], number[1], …, number[n-1] ) + 1;
choosing[ i ] := false;
for j := 0 to n – 1
do begin
while choosing[ j ] do no-op;
while (number[ j ] ≠ 0 and
(number[ j ], j ) < (number[ i ], i ) )do no-op;
done end
critical section
number[ i ] := 0;
remainder section
until false.
Synchronization HardwareSynchronization Hardware
Many systems provide hardware support for critical section
code
Uniprocessors – could disable interrupts
Currently running code would execute without
preemption
Generally too inefficient on multiprocessor systems
Operating systems using this not broadly scalable
Modern machines provide special atomic hardware
instructions
Atomic = non-interruptable
Either test memory word and set value
Or swap contents of two memory words
Low Level Synchronization Tool (LOCK)Low Level Synchronization Tool (LOCK)
Critical section problem could be more simply solved in a uni-processor, if we
could disable interrupt to occur while a shared variable is being modified.
Must ensure that current sequence of instruction would be allowed to execute in
order without preemption.
But disabling interrupts on multiprocessor is time consuming due to message
passing to all processors.
Hence many M/C provide their special H/W instruction for critical section
problem.
A LOCK is a object that provides 2 different operations
 Acquire ( )  wait to enter in to critical section
 Release ( )  allow another to enter in to critical section
acquire_lock ( )
critical section
Release_lock ( )
reminder section
Int withdraw ( account, amount )
{
acquire ( Lock )
balance = get_balance ( account )
balance = balance – amount
put_balance ( account, balance)
release ( Lock )
return ( balance )
}
Implementation of LOCKImplementation of LOCK
Struct lock
{
int held = 0;
}
Void acquire ( lock )
{
while ( lock  held );
lock held = 1;
}
Void release ( lock )
{
lock held = 0;
}
If instruction preempted after while then mutual
exclusion violated. ( Disable Interrupt)
Context switch occurred
Busy wait ( Spin Lock)
Hence, this sequence of instructions must me
atomic.
Atomic  non-interruptable
TestAndndSet InstructionTestAndndSet Instruction
Definition:
Test_Set ( * lock)
{
b = * lock ;
* lock = 1 ;
return b ;
}
Atomic
Shared variable lock initialized to false.
Solution:
repeat
while ( Test_Set (&lock )) do no-op
; /* do nothing
// critical section
lock = FALSE;
// remainder section
Until false
Swap InstructionSwap Instruction
Definition:
void Swap (boolean *a, boolean *b)
{
boolean temp = *a;
*a = *b;
*b = temp:
}
Shared Boolean variable lock initialized
to FALSE;
Each process has a local Boolean
variable key.
Solution:
while (true) {
key = TRUE;
while ( key == TRUE)
Swap (&lock, &key );
// critical section
lock = FALSE;
// remainder section
}
SemaphoreSemaphore
Synchronization tool that does not require busy waiting
Semaphore (S) is an integer variable in which two atomic operations P
& V is defined to provide synchronization & mutual exclusion in
concurrent system.
Two standard operations modify S: wait() and signal()
Originally called P(S) “ TO TEST” and V(S) “TO INCRIMENT”
Less complicated
Can only be accessed via two indivisible (atomic) operations
P(S) : wait (S)
{
while S <= 0; // no-op
S--;
}
V(S) : Signal (S)
{
S++;
}
Semaphore as General Synchronization ToolSemaphore as General Synchronization Tool
Counting semaphore – integer value can range over an
unrestricted domain
Binary semaphore – integer value can range only
between 0 and 1; can be simpler to implement
Also known as mutexlocks
Can implement a counting semaphore S as a binary
semaphore
Provides mutual exclusion
Semaphore S; // initialized to 1
wait (S);
Critical Section
signal (S);
Semaphore ImplementationSemaphore Implementation
Must guarantee that no two processes can execute wait ()
and signal () on the same semaphore at the same time
Thus, implementation becomes critical due to critical
section problem where the wait and signal code both are
placed in the critical section.
Could now have busy waiting in critical section
implementation [which demands mutual exclusion]
Spin Lock
But implementation code is short
Little busy waiting if critical section rarely occupied
Note that applications may spend lots of time in critical
sections and therefore this is not a good solution.
Semaphore Implementation with no Busy waitingSemaphore 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
Two operations:
block – place the process invoking the operation on
the appropriate waiting queue.
wakeup – remove one of processes in the waiting
queue and place it in the ready queue.
Semaphore Implementation with no Busy waitingSemaphore Implementation with no Busy waiting (Cont.)(Cont.)
Implementation of wait:
wait (S){
value--;
if (value < 0) {
add this process to waiting queue
block(); }
}
Implementation of signal:
Signal (S){
value++;
if (value <= 0) {
remove process P from waiting queue
wakeup(P); }
}
Deadlock and StarvationDeadlock 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);
signal (Q); signal (S);
Starvation – indefinite blocking. A process may never be removed
from the semaphore queue in which it is suspended.
Classical Problems of SynchronizationClassical Problems of Synchronization
Bounded-Buffer Problem
Readers and Writers Problem
Dining-Philosophers Problem
Bounded-Buffer ProblemBounded-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.
Bounded Buffer Problem (Cont.)Bounded Buffer Problem (Cont.)
Structure of producer process
while (true) {
// produce an item
wait (empty);
wait (mutex);
// add the item to
the buffer
signal (mutex);
signal (full);
}
Structure of consumer process
while (true) {
wait (full);
wait (mutex);
// remove an item
from buffer
signal (mutex);
signal (empty);
// consume the
removed item
}
N buffers, each can hold one item
Semaphore mutex = 1
Semaphore full = 0
Semaphore empty = N.
Readers-Writers ProblemReaders-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
Semaphore mutex initialized to 1.
Semaphore wrt initialized to 1.
Integer readcount initialized to 0.
Readers-Writers Problem (Cont.)Readers-Writers Problem (Cont.)
Structure of writer
process
while (true)
{
wait (wrt) ;
//writing is
performed
signal (wrt) ;
}
Structure of reader process
while (true)
{
wait (mutex) ;
readcount ++ ;
if (readcount == 1) wait (wrt) ;
signal (mutex)
// reading is performed
wait (mutex) ;
readcount - - ;
if (readcount == 0) signal (wrt) ;
signal (mutex)
}
Dining-Philosophers ProblemDining-Philosophers Problem
Shared data
Bowl of rice (data set)
Semaphore chopstick [5] initialized to 1
P4 P0
P3 P1
P2
S0
S1S2
S3
S4
Dining-Philosophers Problem (Cont.)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] );
// think
}
Problems with SemaphoresProblems with Semaphores
Incorrect use of semaphore operations:
signal (mutex) …. wait (mutex)
wait (mutex) … wait (mutex)
Omitting of wait (mutex) or signal (mutex) (or both)
Operating System
Critical Regions
• High-level synchronization construct
• A shared variable v of type T, is declared as:
var v: shared T
• Variable v accessed only inside statement
region v when B do S
 where B is a Boolean expression that governs the access
to critical regions..
 While statement S is being executed, no other process
can access variable v.
Operating System
Critical Regions (Cont.)
• Regions referring to the same shared
variable exclude each other in time.
• When a process tries to execute the region
statement, the Boolean expression B is
evaluated.
– If B is true, statement S is executed.
– If it is false, the process is delayed until B
becomes true and no other process is in the
region associated with v.
Operating System
Example – Bounded Buffer
• Shared variables:
var buffer: shared record
pool: array [0..n–1] of item;
count,in,out: integer
end;
• Producer process inserts nextp into the shared buffer
region buffer when count < n
do begin
pool[in] := nextp;
in:= in+1 mod n;
count := count + 1;
end;
Operating System
Bounded Buffer Example (Cont.)
• Consumer process removes an item from the
shared buffer and puts it in nextc
region buffer when count > 0
do begin
nextc := pool[out];
out := out+1 mod n;
count := count – 1;
end;
MonitorsMonitors
A high-level abstraction that provides a convenient and effective mechanism for
process synchronization
Only one process may be active within the monitor at a time
type monitor-name = monitor
variable declarations
// Shared variable declarations
procedure entry P1 :(…);
begin … end;
procedure entry P2(…);
begin … end;

procedure entry Pn (…);
begin…end;
begin
initialization code
end
Schematic view of a MonitorSchematic view of a Monitor
Condition VariablesCondition Variables
• To allow a process to wait within the monitor, a condition
variable must be declared, as
var x, y: condition
• Condition variable can only be used with the operations wait
and signal.
– The operation
x.wait;
means that the process invoking this operation is suspended until
another process invokes
x.signal;
– The x.signal operation resumes exactly one suspended process. If
no process is suspended, then the signal operation has no effect.
Monitor with Condition VariablesMonitor with Condition Variables
End of Chapter 4End of Chapter 4

Operating System

  • 1.
    ProcessProcess SynchronizationSynchronization Mr. SUBHASIS DASH SCHOLEOF COMPUTER ENGINEERING. KIIT UNIVERSITY BHUBANESWAR
  • 2.
    Cooperating ProcessesCooperating Processes Independentprocess cannot affect or be affected by the execution of another process Cooperating process can affect or be affected by the execution of another process Advantages of process cooperation Information sharing Computation speed-up Modularity Convenience
  • 3.
    Producer-Consumer ProblemProducer-Consumer Problem Paradigmfor cooperating processes, producer process produces information that is consumed by a consumer process unbounded-buffer places no practical limit on the size of the buffer bounded-buffer assumes that there is a fixed buffer size
  • 4.
    Bounded-Buffer – Shared-MemorySolutionBounded-Buffer – Shared-Memory Solution Shared data #define BUFFER_SIZE n typedef struct { . . . } item; item buffer[BUFFER_SIZE]; int in = 0; int out = 0; Solution is correct, but can only use BUFFER_SIZE is [n-1] elements. ( ( ( in = ( in + 1 ) % BUFFER SIZE count) == out) :- buffer full (in == out) :- buffer empty
  • 5.
    BackgroundBackground Concurrent access toshared data may result in data inconsistency Maintaining data consistency requires mechanisms to ensure the orderly execution of cooperating processes Suppose that we wanted to provide a solution to the consumer- producer problem that fills all the buffers. We can do so by having an integer count that keeps track of the number of full buffers. Initially, count is set to 0. It is incremented by the producer after it produces a new buffer and is decremented by the consumer after it consumes a buffer.
  • 6.
    ProducerProducer while (true) { /*produce an item and put in nextProduced */ while (count == BUFFER_SIZE) ; // do nothing buffer [in] = nextProduced; in = (in + 1) % BUFFER_SIZE; count++; }
  • 7.
    ConsumerConsumer while (true) { while(count == 0) ; // do nothing nextConsumed = buffer[out]; out = (out + 1) % BUFFER_SIZE; count--; /* consume the item in nextConsumed }
  • 8.
    Producer & ConsumerCodeProducer & Consumer Code while (true) { /* produce an item and put in next Produced */ while (count == BUFFER_SIZE); // do nothing buffer [in] = nextProduced; in = (in + 1) % BUFFER_SIZE; count++; } while (true) { while (count == 0); // do nothing nextConsumed = buffer[out]; out = (out + 1) % BUFFER_SIZE; count--; /* consume the item in next Consumed */ }
  • 9.
    Race ConditionRace Condition count++could be implemented as register1 = count register1 = register1 + 1 count = register1 count-- could be implemented as register2 = count register2 = register2 - 1 count = register2 Consider this execution interleaving with “count = 5” initially: S0: producer execute register1 = count {register1 = 5} S1: producer execute register1 = register1 + 1 {register1 = 6} S2: consumer execute register2 = count {register2 = 5} S3: consumer execute register2 = register2 - 1 {register2 = 4} S4: producer execute count = register1 {count = 6 } S5: consumer execute count = register2 {count = 4}
  • 10.
    CRITICAL SECTION (CS)PROBLEMCRITICAL SECTION (CS) PROBLEM Critical is a segment of code in each process where process wants to change there common variable. But CS allows only one process to execute in its CS –: MUTUALLYMUTUALLY EXCLUSIVEEXCLUSIVE. There are 3 different sections:- ENTRY SECTION EXIT SECTION REMINDER SECTION Example:- repeat ENTRY critical section EXIT reminder section until false
  • 11.
    Solution to Critical-SectionProblemSolution to 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 only those process that are not executing their reminder section can participate in the selection of the processes that which will enter the critical section next, and this selection cann’t 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
  • 12.
    11stst S/W Solution forCS problemS/W Solution for CS problem PI’s Algorithm repeat var turn = i While ( turn != “ i ”) do no-op; Critical section turn=“ j ”; until false PJ’s Algorithm repeat var turn = j While ( turn != “ j ”) do no-op; Critical section turn=“ i ”; until false
  • 13.
    22ndnd SolutionSolution PI’s Algorithm Var flag: array [ i…j] of boolen repeat flag [i] = true; While ( flag [j] == “ true ”) do no-op; Critical section Flag [i]=“ false ”; until false PJ’s Algorithm Var flag : array [ i…j] of boolen repeat flag [ j ] = true; While ( flag [ i ] == “ true ”) do no-op; Critical section Flag [j]=“ false ”; until false
  • 14.
    Peterson’s Two ProcessSolutionPeterson’s Two Process Solution Two process solution Assume that the LOAD and STORE instructions are atomic; that is, cannot be interrupted. 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!
  • 15.
    Peterson’s SolutionPeterson’s Solution PI’sAlgorithm repeat S1: flag [ i ] = TRUE; S2: turn = j; S3: while ( flag[ j ] == TRUE && turn != i ) do no-op; CRITICAL SECTION flag [ i ] = FALSE; until false PJ’s Algorithm repeat L1: flag [ j ] = TRUE; L2: turn = i; L3: while ( flag [ i ] == TRUE && turn != j) do no-op; CRITICAL SECTION flag [ j ] = FALSE; until false Sequence of execution: S1; S2; L1;L2; S1;L1;L2;S2; L1;S1;L2;S2
  • 16.
    The Bakery Algorithm(N process Solution)The Bakery Algorithm (N process Solution) Generalization for n processes (Customers). Each process has an ID (Customers IDs are in order). Before entering its critical section, A process receives a number (in order). Process holds smallest number enters in to its critical section first. Drawback Can not guarantee that two processes (Customers) do not receive the same number (Tie). Tie breaker is done using the process id (Custer with lower customer ID is served first) if processes i and j hold the same number and i < j then i enters first.
  • 17.
    The Bakery Algorithm(N process Solution)The Bakery Algorithm (N process Solution) Data Structure Common Variable  choosing[0…..n-1] of boolean  number[0….n-1] of integer Initially  choosing [i] = false  number [i] = 0 Notation  ( a, b ) < ( c, d ) if a < c or if a = c & b < d Number ID Number ID
  • 18.
    The Bakery Algorithm(N process Solution)The Bakery Algorithm (N process Solution) Repeat choosing[ i ] := true; number[ i ] :=max ( number[0], number[1], …, number[n-1] ) + 1; choosing[ i ] := false; for j := 0 to n – 1 do begin while choosing[ j ] do no-op; while (number[ j ] ≠ 0 and (number[ j ], j ) < (number[ i ], i ) )do no-op; done end critical section number[ i ] := 0; remainder section until false.
  • 19.
    Synchronization HardwareSynchronization Hardware Manysystems provide hardware support for critical section code Uniprocessors – could disable interrupts Currently running code would execute without preemption Generally too inefficient on multiprocessor systems Operating systems using this not broadly scalable Modern machines provide special atomic hardware instructions Atomic = non-interruptable Either test memory word and set value Or swap contents of two memory words
  • 20.
    Low Level SynchronizationTool (LOCK)Low Level Synchronization Tool (LOCK) Critical section problem could be more simply solved in a uni-processor, if we could disable interrupt to occur while a shared variable is being modified. Must ensure that current sequence of instruction would be allowed to execute in order without preemption. But disabling interrupts on multiprocessor is time consuming due to message passing to all processors. Hence many M/C provide their special H/W instruction for critical section problem. A LOCK is a object that provides 2 different operations  Acquire ( )  wait to enter in to critical section  Release ( )  allow another to enter in to critical section acquire_lock ( ) critical section Release_lock ( ) reminder section Int withdraw ( account, amount ) { acquire ( Lock ) balance = get_balance ( account ) balance = balance – amount put_balance ( account, balance) release ( Lock ) return ( balance ) }
  • 21.
    Implementation of LOCKImplementationof LOCK Struct lock { int held = 0; } Void acquire ( lock ) { while ( lock  held ); lock held = 1; } Void release ( lock ) { lock held = 0; } If instruction preempted after while then mutual exclusion violated. ( Disable Interrupt) Context switch occurred Busy wait ( Spin Lock) Hence, this sequence of instructions must me atomic. Atomic  non-interruptable
  • 22.
    TestAndndSet InstructionTestAndndSet Instruction Definition: Test_Set( * lock) { b = * lock ; * lock = 1 ; return b ; } Atomic Shared variable lock initialized to false. Solution: repeat while ( Test_Set (&lock )) do no-op ; /* do nothing // critical section lock = FALSE; // remainder section Until false
  • 23.
    Swap InstructionSwap Instruction Definition: voidSwap (boolean *a, boolean *b) { boolean temp = *a; *a = *b; *b = temp: } Shared Boolean variable lock initialized to FALSE; Each process has a local Boolean variable key. Solution: while (true) { key = TRUE; while ( key == TRUE) Swap (&lock, &key ); // critical section lock = FALSE; // remainder section }
  • 24.
    SemaphoreSemaphore Synchronization tool thatdoes not require busy waiting Semaphore (S) is an integer variable in which two atomic operations P & V is defined to provide synchronization & mutual exclusion in concurrent system. Two standard operations modify S: wait() and signal() Originally called P(S) “ TO TEST” and V(S) “TO INCRIMENT” Less complicated Can only be accessed via two indivisible (atomic) operations P(S) : wait (S) { while S <= 0; // no-op S--; } V(S) : Signal (S) { S++; }
  • 25.
    Semaphore as GeneralSynchronization ToolSemaphore as General Synchronization Tool Counting semaphore – integer value can range over an unrestricted domain Binary semaphore – integer value can range only between 0 and 1; can be simpler to implement Also known as mutexlocks Can implement a counting semaphore S as a binary semaphore Provides mutual exclusion Semaphore S; // initialized to 1 wait (S); Critical Section signal (S);
  • 26.
    Semaphore ImplementationSemaphore Implementation Mustguarantee that no two processes can execute wait () and signal () on the same semaphore at the same time Thus, implementation becomes critical due to critical section problem where the wait and signal code both are placed in the critical section. Could now have busy waiting in critical section implementation [which demands mutual exclusion] Spin Lock But implementation code is short Little busy waiting if critical section rarely occupied Note that applications may spend lots of time in critical sections and therefore this is not a good solution.
  • 27.
    Semaphore Implementation withno Busy waitingSemaphore 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 Two operations: block – place the process invoking the operation on the appropriate waiting queue. wakeup – remove one of processes in the waiting queue and place it in the ready queue.
  • 28.
    Semaphore Implementation withno Busy waitingSemaphore Implementation with no Busy waiting (Cont.)(Cont.) Implementation of wait: wait (S){ value--; if (value < 0) { add this process to waiting queue block(); } } Implementation of signal: Signal (S){ value++; if (value <= 0) { remove process P from waiting queue wakeup(P); } }
  • 29.
    Deadlock and StarvationDeadlockand 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); signal (Q); signal (S); Starvation – indefinite blocking. A process may never be removed from the semaphore queue in which it is suspended.
  • 30.
    Classical Problems ofSynchronizationClassical Problems of Synchronization Bounded-Buffer Problem Readers and Writers Problem Dining-Philosophers Problem
  • 31.
    Bounded-Buffer ProblemBounded-Buffer Problem Nbuffers, 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.
  • 32.
    Bounded Buffer Problem(Cont.)Bounded Buffer Problem (Cont.) Structure of producer process while (true) { // produce an item wait (empty); wait (mutex); // add the item to the buffer signal (mutex); signal (full); } Structure of consumer process while (true) { wait (full); wait (mutex); // remove an item from buffer signal (mutex); signal (empty); // consume the removed item } N buffers, each can hold one item Semaphore mutex = 1 Semaphore full = 0 Semaphore empty = N.
  • 33.
    Readers-Writers ProblemReaders-Writers Problem Adata 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 Semaphore mutex initialized to 1. Semaphore wrt initialized to 1. Integer readcount initialized to 0.
  • 34.
    Readers-Writers Problem (Cont.)Readers-WritersProblem (Cont.) Structure of writer process while (true) { wait (wrt) ; //writing is performed signal (wrt) ; } Structure of reader process while (true) { wait (mutex) ; readcount ++ ; if (readcount == 1) wait (wrt) ; signal (mutex) // reading is performed wait (mutex) ; readcount - - ; if (readcount == 0) signal (wrt) ; signal (mutex) }
  • 35.
    Dining-Philosophers ProblemDining-Philosophers Problem Shareddata Bowl of rice (data set) Semaphore chopstick [5] initialized to 1 P4 P0 P3 P1 P2 S0 S1S2 S3 S4
  • 36.
    Dining-Philosophers Problem (Cont.)Dining-PhilosophersProblem (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] ); // think }
  • 37.
    Problems with SemaphoresProblemswith Semaphores Incorrect use of semaphore operations: signal (mutex) …. wait (mutex) wait (mutex) … wait (mutex) Omitting of wait (mutex) or signal (mutex) (or both)
  • 38.
    Operating System Critical Regions •High-level synchronization construct • A shared variable v of type T, is declared as: var v: shared T • Variable v accessed only inside statement region v when B do S  where B is a Boolean expression that governs the access to critical regions..  While statement S is being executed, no other process can access variable v.
  • 39.
    Operating System Critical Regions(Cont.) • Regions referring to the same shared variable exclude each other in time. • When a process tries to execute the region statement, the Boolean expression B is evaluated. – If B is true, statement S is executed. – If it is false, the process is delayed until B becomes true and no other process is in the region associated with v.
  • 40.
    Operating System Example –Bounded Buffer • Shared variables: var buffer: shared record pool: array [0..n–1] of item; count,in,out: integer end; • Producer process inserts nextp into the shared buffer region buffer when count < n do begin pool[in] := nextp; in:= in+1 mod n; count := count + 1; end;
  • 41.
    Operating System Bounded BufferExample (Cont.) • Consumer process removes an item from the shared buffer and puts it in nextc region buffer when count > 0 do begin nextc := pool[out]; out := out+1 mod n; count := count – 1; end;
  • 42.
    MonitorsMonitors A high-level abstractionthat provides a convenient and effective mechanism for process synchronization Only one process may be active within the monitor at a time type monitor-name = monitor variable declarations // Shared variable declarations procedure entry P1 :(…); begin … end; procedure entry P2(…); begin … end;  procedure entry Pn (…); begin…end; begin initialization code end
  • 43.
    Schematic view ofa MonitorSchematic view of a Monitor
  • 44.
    Condition VariablesCondition Variables •To allow a process to wait within the monitor, a condition variable must be declared, as var x, y: condition • Condition variable can only be used with the operations wait and signal. – The operation x.wait; means that the process invoking this operation is suspended until another process invokes x.signal; – The x.signal operation resumes exactly one suspended process. If no process is suspended, then the signal operation has no effect.
  • 45.
    Monitor with ConditionVariablesMonitor with Condition Variables
  • 46.
    End of Chapter4End of Chapter 4