Here's the Test and Set written in software:
boolean TestAndSet(boolean *target) {
boolean rv = *target;
*target = TRUE;
return rv;
}
and
do {
while(TestAndSetLock(&lock))
; // do nothing
// critical section
lock = FALSE;
// remainder section
} while(TRUE);
Can we use the mechanism in CPUs that do not support test-and-set at the hardware level? If so, how is atomicity assured?
You can use Lamport's 'bakery' mutual exclusion algorithm on machines w/o TAS/CAS to gate access to the 'atomic' (protected) value.
http://www.disi.unige.it/person/DelzannoG/SO1/AA0607/bakery.htm
It only gets complicated if you don't have a reasonably limited 'N' processes.
Test and Set cannot be implemented in software without hardware support the way you proposed.
It is because TestAndSet
above is supposed to be a mechanism to be used to ensure mutual exclusion, but it is not atomic. Atomicity, however, is just another name for mutual exclusion: the internal variables of TestAndSet
must be protected by ensuring that two processes cannot execute its code concurrently.
So this way you defined a method for ensuring mutual exclusion which itself requires some mechanism to ensure mutual exclusion. This trick can be played a number of times, but there will not be any real progress without some sort of hardware support.