0

I am going through this chapter https://pages.cs.wisc.edu/~remzi/OSTEP/threads-locks.pdf , I read the author mentioning Test-And-Set and CompareAndSwap's being atomic. Please find the code snippets below

int TestAndSet(int *old_ptr, int new) {
   int old = *old_ptr; // fetch old value at old_ptr
   *old_ptr = new; // store ’new’ into old_ptr
   return old; // return the old value
  }
    void lock(lock_t *lock) {
      while (TestAndSet(&lock->flag, 1) == 1)
        ; // spin-wait (do nothing)  }

I wanna understand if in this code above, what happens if an interrupt happens at lines int old = *old_ptr and next thread starts executing after the interrupt. and similarly,

int CompareAndSwap(int *ptr, int expected, int new) {
 int original = *ptr;
 if (original == expected)
 *ptr = new;
 return original;
}

void lock(lock_t *lock) { while (CompareAndSwap(&lock->flag, 0, 1) == 1) ; // spin }

in this code above, if an interrupt happens at line int original = *ptr; and next thread starts after interrupt?

Vivek Anand
  • 103
  • 2

1 Answers1

0

TestAndSet is only atomic if the hardware provides an implementation that is atomic. For instance, some CPUs provide a special instruction that does a TestAndSet, and is guaranteed to be atomic.

If you try to implement it in code following the example code in your question, that implementation will not be atomic. That code is presumably intended to illustrate the semantics of TestAndSet, but it is not how we would actually implement it in practice.

The same applies to CompareAndSwap.

See also https://en.wikipedia.org/wiki/Test-and-set, https://en.wikipedia.org/wiki/Compare-and-swap.

D.W.
  • 167,959
  • 22
  • 232
  • 500