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?