PROCESS SYNCHRONIZATION Dsatm
PROCESS SYNCHRONIZATION Dsatm
PROCESS SYNCHRONIZATION Dsatm
Process Synchronization
Basics:
while (true) {
while (counter == 0)
; /* do nothing */
next_consumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
counter--;
/* consume the item in next consumed */
}
Operating Systems Module 2
Race condition: where several process access and manipulate the same
data concurrently and the outcome of execution depends on the
particular order in which access takes place.
Peterson’s Solution
For p0
flag[0] = true;
turn = 1;
while (flag[1] && turn = = 1);
critical section
flag[0] = false;
For p1
flag[1] = true;
turn = 0;
while (flag[0] && turn = = 0);
critical section
flag[1] = false;
Operating Systems Module 2
Synchronization Hardware
Many systems provide hardware support for implementing the critical
section code.
All solutions below based on idea of locking
Protecting critical regions via locks
test_and_set Instruction
boolean test_and_set (boolean *target)
{
boolean rv = *target;
*target = TRUE;
return rv:
}
1. Executed atomically
2. Returns the original value of passed parameter
3. Set the new value of passed parameter to “TRUE”.
Shared Boolean variable lock, initialized to FALSE
Solution:
do {
while (test_and_set(&lock));
/* critical section */
lock = false;
/* remainder section */
} while (true);
Swap Instruction
void Swap (boolean *a, boolean *b)
{
boolean temp = *a;
*a = *b;
*b = temp:
}
Operating Systems Module 2
Semaphore
Synchronization tool that provides more sophisticated ways (than Mutex
locks) for process to synchronize their activities.
Semaphore S – integer variable
Can only be accessed via two indivisible (atomic) operations
o wait() and signal()
Originally called P() and V()
Definition of the wait() operation
wait(S) {
while (S <= 0)
; // busy wait
S--;
}
Definition of the signal() operation
signal(S) {
S++;
}