The book Operating System Principles by Silberschatz, Galvin, and Gagne has the following implementation for atomic operations of test_and_set
boolean test_and_set(boolean *target) {
boolean rv = *target;
*target = true;
return rv;
}
They declared a global variable lock initialized to 0 and used the following implementation of the mutex for each process
do {
while(test_and_set(&lock))
; // do nothing
// critical section
lock = false;
// remainder section
} while(true);
Now, let's consider the situation when process P0 is implementing the critical section and process P1 is stuck at the while loop. Consider the following order of execution then
//lock = true initially because P0 is in critical section
P1 boolean rv = *target; //rv = true, lock = true
//P0 now completed its critical section and is ready to leave the lock
P0 lock = false //rv = true, lock = false
P1 *target = true; //rv = true, lock = true
P1 return rv; // returns true
So, the process P0 or any other as a matter of fact cannot enter the critical section forever. How does this handle this case then?