Synchronization
Synchronization
Synchronization
• Background
• The Critical-Section Problem
• Synchronization Hardware
• Semaphores
• Classical Problems of Synchronization
• Critical Regions
• Consumer process
repeat
while counter = 0 do no-op;
nextc := buffer [out];
out := out + 1 mod n;
counter := counter – 1;
…
consume the item in nextc
…
until false;
• The statements:
repeat
entry section
critical section
exit section
until false;
• Processes may share some common variables to
synchronize their actions.
Algorithm
•Shared variables:
1
var turn: (0..1);
initially turn = 0
turn - i Pi can enter its critical section
• Process Pi
repeat
while turn i do no-op;
critical section
turn := j;
• Process Pi
repeat
flag[i] := true;
remainder section
until false;
Algorithm 3
• Combined shared variables of algorithms 1 and 2.
• Process Pi
repeat
flag [i] := true;
turn := j;
while (flag [j] and turn = j) do no-op;
critical section
flag [i] := false;
• Shared data
begin
Test-and-Set := target;
target := true;
end;
• Process Pi
repeat
critical section
lock := false;
until false;
Swap() instruction
void swap(Boolean *a, Boolean *b)
{ Boolean temp=*a;
*a=*b
*b=temp;
do{ key=True
while(key ==True)
//critical section
lock=False;
//remainder section
}while(TRUE)
Semaphore
• Synchronization tool
• Semaphore S – integer variable
• can only be accessed via two indivisible (atomic)
operations
• Shared variables
var mutex : semaphore
initially mutex = 1
• Process Pi
repeat
wait(mutex);
signal(mutex);
remainder section
until false;
Semaphore
Implementation
• Define a semaphore as a record
value: integer
L: list of process;
end;
• Assume two simple operations:
if S.value < 0
then begin
end;
then begin
end;
Semaphore as General
Synchronization Tool
Pi Pj
A wait(flag)
• Data structures:
var S1: binary-semaphore;
S2: binary-semaphore;
S3: binary-semaphore;
C: integer;
• Initialization:
S1 = S3 = 1
S2 = 0
• Writer process
wait(wrt);
…
writing is performed
signal(mutex):
Dining-Philosophers
Problem
var v: shared T
• Variable v accessed only inside statement
region v when B do S
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
end;
begin
for i := 0 to 4
• Variables
var mutex: semaphore (init = 1)
next: semaphore (init = 0)
next-count: integer (init = 0)
• Each external procedure F will be replaced by
wait(mutex);
…
body of F;
x-count := x-count + 1;
if next-count >0
then signal(next)