Critical Section Problem
Critical Section Problem
Critical Section Problem
do {
acquire lock
critical section
release lock
remainder section
} while (TRUE);
1.test_and_set Instruction
Definition:
boolean test_and_set (boolean *target)
{
boolean rv = *target;
*target = TRUE;
return rv:
}
1. This instruction is atomic
2. This instruction is provided by the hardware
Solution using test_and_set()
Definition:
void Swap(boolean *a, boolean *b)
{
boolean temp = *a;
*a *b;
*b = temp;
}
1. This instruction is atomic
2. This instruction is provided by the hardware
Solution using swap()
• Shared Boolean variable lock initialized to False
• Each process has a local boolean variable key
do
{
key = TRUE;
while (key == TRUE)
Swap(&lock, &key);
critical section
lock = FALSE;
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);