In comparison to Test and Set Instruction, the compare and swap instruction operates on three operands.
Here the operand value is assigned to a new value only if the expression (*value == expected) is true. Regardless, compare_and_swap() always returns the original value of the variable value. Like the test and set instruction, compare_and_swap() is integrated instruction that runs automatically.
# Let's take an example to make it more clear.
Example: Check for Mutual Exclusion
Initially Lock = 0
Assume two processes are running P0, P1 is as below:
P0: 1, 2 (CS) | P1: 1
# P0 executes instruction 1, initially lock = 0 so, it is matched with the second parameter of the function expected value of 0 and then assign new value 1 (as the third parameter) to lock, now lock = 1.
As we know the whole function compare_and_swap returns the main initial value of the lock i.e. lock = 0. So, it satisfied and executes instruction 2 and enters into its critical section. After that P0 preempted.
# P1 gets the CPU and executes instruction 1, right now lock = 1. It is not matched with the second parameter of the function expected value of 0. So, it does not assign a new value 1 (as the third parameter) to lock.
As we know whole function compare_and_swap returns the main initial value of the lock i.e. lock=1. So, it not satisfied and stuck in instructions 1 (while loop) i.e. busy waiting until lock=0.
Compare and Swap instruction satisfy mutual exclusion.
Test and Set Instructions
1. Mutual Exclusion: Yes
2. Progress: Yes
3. Bounded waiting: No
4. Portability: No (because compare_and_swap is OS instruction)