Blocking Synchronization: Semaphores Condition Regions Monitors
Blocking Synchronization: Semaphores Condition Regions Monitors
Semaphores
Condition regions
Monitors
Semaphores
Initialization(val)
{
v = val ;
L = ^;
}
P(s)
v--;
if(v < 0)
{
add thread to L;
block;
}
This code executes atomically.
V(s)
v++;
if(v £ 0)
{
Remove a thread T from L;
Unblock(T);
}
This code executes atomically.
Important Properties
Two types:
Counting semaphores
v takes any values
Binary semaphores
v takes only 0 or 1
P(s): Binary Semaphores
if(v == 0) executes
{ atomically
Add caller to L;
Block;
}
else
v--;
V(s): Binary Semaphores
region v when B do S ;
x = 0; Thread T1, T2
Monitor M {
int a, b, c ;
condition x, y, z ;
fn1(…);
fn2(…);
…
fnm(…);}
Example Declaration (cont’d)
M(…)
{
/* initialization code */
}
fn1(…)
…
x.wait // T1 blocks fn4(…)
…
x.signal // T2 blocks
// T1 resumes
// T1 finishes
// T2 resumes
Example: Hansen Monitors
fn1(…)
…
x.wait // T1 blocks fn4(…)
…
x.signal // T2 continues
// T2 finishes
// T1 resumes
// T1 finishes
Tradeoff
Hoare Hansen
Awkward in programming Easier to program
Cleaner, good for Can lead to synchronization
mathematical proofs bugs
Main advantage: when a
condition variable is
signalled, condition does
not change
Example
fn()
{
…
x.signal
}
A Hoare monitor forces thread to block needlessly in
this example
Example: Java