os5
os5
Prepared By
Background
The Critical-
Section Problem
Peterson’s Solution
Synchronization
Hardware
Mutex Locks
Background
while (true) {
/* produce an item in next produced */
while (true) {
while (counter == 0)
; /* do nothing */
next_consumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
counter--;
/* consume the item in next consumed */
}
Race Condition
register1 = counter
register1 = register1 + 1
counter = register1
• counter-- could be implemented as
register2 = counter
register2 = register2 - 1
counter = register2
Each process must ask permission to enter critical section in entry section,
may follow critical section with exit section, then remainder section
Critical Section
do {
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
Critical-Section Handling in OS
do {
flag[i] = true;
turn = j;
critical section
flag[i] = false;
remainder section
} while (true);
Peterson’s Solution (Cont.)
Many systems provide hardware support for implementing the critical section
code.
All solutions below based on idea of locking
• Atomic = non-interruptible
– Either test memory word and set value
– Or swap contents of two memory words
Solution to Critical-section Problem
Using Locks
do {
acquire lock
critical section
release lock
remainder section
} while (TRUE);
test_and_set Instruction
Definition:
boolean rv = *target;
*target = TRUE;
return rv:
1. Executed atomically
Definition:
if (*value == expected)
*value = new_value;
return temp;
1. Executed atomically
3. Set the variable “value” the value of the passed parameter “new_value” but
only if “value” ==“expected”. That is, the swap takes place only under this
Solution using compare_and_swap
do{
while (compare_and_swap(&lock, 0, 1) != 0)
; /* do nothing */
/* critical section */
lock = 0;
/* remainder section */
} while (true);
Bounded-waiting Mutual Exclusion with
test_and_set
do {
waiting[i] = true;
key = true;
while (waiting[i] && key)
key = test_and_set(&lock);
waiting[i] = false;
/* critical section */
j = (i + 1) % n;
while ((j != i) && !waiting[j])
j = (j + 1) % n;
if (j == i)
lock = false;
else
waiting[j] = false;
/* remainder section */
} while (true);
Mutex Locks
• acquire() {
while (!available)
; /* busy wait */
available = false;
}
• release() {
available = true;
}
• do {
acquire lock
critical section
release lock
remainder section
} while (true);