7

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?

Arjun Sreedharan
  • 11,003
  • 2
  • 26
  • 34
  • There are programmed synchronization algorithms (not test and set, but you can still set up reliable interlocks) such as Dekker's algorithm, that only rely on atomicity of reads and writes to memory. Without such atomicity on reads and writes, its hard to see how to code any kind of spin loop waiting for another process to complete; you could never trust that a processor-complete flag you were inspecting, was reliable. – Ira Baxter Aug 04 '14 at 11:18
  • Concerning Dekker's algorithm: You need to be aware of hardware mechanism potentially breaking the algorithm. E.g. write-to-read ordering on IBM-370. – Philipp Aug 04 '14 at 15:47

2 Answers2

1

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.

dbrower
  • 254
  • 2
  • 9
1

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.

xxa
  • 1,258
  • 9
  • 20