inefficient spinning Flashcards
(4 cards)
do {
while (TestAndSet(&lock)) ;
[critical section]
lock = FALSE; // Release lock
[remainder section]
} while (TRUE);
even though this code achieves mutual exlusion there is a flaw, what is it?
This guarantees mutual exclusion but with a high cost: that while loop spins constantly (using up CPU cycles) until it manages to enter the critical section.
This is a huge waste of CPU cycles and is not acceptable,
particularly for user processes where the critical section maybe occupied for some time
how to avoid cpu constanly cycling
we implement some mechanism whereby it sends itself to sleep and then is awoken only when there is a chance it can proceed Functions such as sleep() and wakeup() are often available
via a threading library or as kernel service calls
code for Mutual Exclusion with sleep()
do {
while (TestAndSet(&lock)) { // If we can’t get the lock, sleep.
sleep();
}
[critical section]
wake_up(all); // Wake all sleeping threads.
lock = FALSE; // Release lock
[remainder section]
} while (TRUE);
what does this code show
do {
while (TestAndSet(&lock)) { sleep.
sleep();
}
[critical section]
wake_up(all); // Wake all sleeping threads.
lock = FALSE; // Release lock
[remainder section]
} while (TRUE);
The Missing Wake-up Problem
Mutual Exclusion with sleep(): A first Attempt
If constant spinning is a problem, suppose a process puts itself
to sleep in the body of the spin.
Then whoever won the competition (and therefore entered the
critical section) will wake all processes before releasing the
lock - so they can all try again