Could someone explain to me the working and differences of above operations in multi-threading?
2 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.

- 97,037
- 24
- 136
- 212
-
Since `compare-and-swap` does more work than `test-and-set` does it take more time than `test-and-set`? – arunmoezhi Mar 29 '14 at 18:02
-
@arunmoezhi, it depends on implementation. – Kirill V. Lyadvinsky Mar 31 '14 at 05:51
-
Can you please elaborate. The reason why I'm interested in this is if test-and-set is faster then I can modify my algorithm to use it instead of compare-and-swap – arunmoezhi Mar 31 '14 at 13:32
-
1Here're some code examples: https://www.cs.cornell.edu/courses/cs4410/2015su/lectures/lec06-spin.html – yyFred Mar 27 '21 at 04:29
Test and set operates on a bit, compare and swap operates on a 32-bit field.
The z/TPF system favors the use of the test and set (TS) instruction because frequently, lock indicators are bits that are set to control access to critical regions of system code. The test and set (TS) instruction requires fewer registers than the compare and swap (CS) instruction and requires less execution time because only a single byte needs to be set.
and, I found these materials from : http://www.ibm.com/support/knowledgecenter/SSB23S_1.1.0.13/gtpc3/tasinst.html
you can learn more about TSL with the book called "Modern Operating System,Chapter 2"...

- 119
- 1
- 4