Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare and swap vs test and set

Could someone explain to me the working and differences of above operations in multi-threading?

like image 232
Tony The Lion Avatar asked Sep 07 '10 14:09

Tony The Lion


People also ask

Why is compare and swap better than test-and-set?

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.

What is compare and swap used for?

Compare and swap is a technique used when designing concurrent algorithms. Basically, compare and swap compares the value of a variable with an expected value, and if the values are equal then swaps the value of the variable for a new value.

How is compare and swap implemented?

Compare and swap is a technique used when designing concurrent algorithms. The approach is to compare the actual value of the variable to the expected value of the variable and if the actual value matches the expected value, then swap the actual value of the variable for the new value passed in.

What is a test-and-set instruction?

In computer science, the test-and-set instruction is an instruction used to write (set) 1 to a memory location and return its old value as a single atomic (i.e., non-interruptible) operation. The caller can then "test" the result to see if the state was changed by the call.


1 Answers

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.

The difference marked in bold.

like image 176
Kirill V. Lyadvinsky Avatar answered Oct 07 '22 15:10

Kirill V. Lyadvinsky