lecture 5
lecture 5
LECTURE 5
SYNCHRONIZATION
while (true)
{
/* produce an item and put in next Produced*/
while (count == BUFFER_SIZE) ; // do nothing
buffer [in] = next Produced;
in = (in + 1);
count++;
}
CONSUMER
while (true)
{
while (count == 0) ; // do nothing next
Consumed= buffer[out];
out = (out + 1);
count--;
/* consume the item in next Consumed
}
RACE 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
CONTINUE…
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!
PROCESS ALGORITHM FOR PROCESS PI
while (true)
{
flag[i] = TRUE;
turn = j;
while ( flag[j]==TRUE&& turn == j);
CRITICAL SECTION
flag[i] = FALSE;
REMAINDER SECTION
}
SYNCHRONIZATION HARDWARE
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
SEMAPHORE
SEMAPHORE
Synchronization tool that does not require busy waiting Semaphore S–integer variable
Two standard operations modify S: wait()and signal()
Originally called P() and V() Less complicated Can only be accessed via two indivisible
(atomic) operations
wait (S)
{
while S <= 0 ; // no-op
S--;
}
signal (S)
{
S++;
}
SEMAPHORE AS GENERAL SYNCHRONIZATION TOOL
Must guarantee that no two processes can execute wait ()and signal ()on the same
semaphore at the same time
Thus, implementation becomes the critical section problem where the wait and
signal code are placed in the critical section.
Could now have busy waiting in critical section implementation
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 WAITING