Mona Jalal
Mona Jalal

Reputation: 38255

Why CompareAndSwap is more of a powerful instruction than TestAndSet?

Please consider the following piece of code for CompareAndSwap and let me know why this atomic instruction is more powerful than atomic TestAndSet for being a mutual exclusion primitive?

char CompareAndSwap(int *ptr, int old, int new) {
unsigned char ret;
// Note that sete sets a ’byte’ not the word
__asm__ __volatile__ (
" lock\n"
" cmpxchgl %2,%1\n"
" sete %0\n"
: "=q" (ret), "=m" (*ptr)
: "r" (new), "m" (*ptr), "a" (old)
: "memory");
return ret;
}

Upvotes: 1

Views: 1601

Answers (1)

Parth Patel
Parth Patel

Reputation: 19

test-and-set modifies the contents of a memory location and returns its old value as a single atomic operation.

compare-and-swap atomically compares the contents of a memory location to a given value and, only if they are the same, modifies the contents of that memory location to a given new value.

Upvotes: 1

Related Questions