Home > Mobile >  Does the technique compare-and-swap PREVENT accessing the same memory location concurrently?
Does the technique compare-and-swap PREVENT accessing the same memory location concurrently?

Time:11-04

Does a CAS operation guarantee that no other thread will access the same memory location in question (during the process) AT THE SAME TIME or what does the bold text refer to?

https://en.wikipedia.org/wiki/Compare-and-swap

In computer science, compare-and-swap (CAS) is an atomic instruction used in multithreading to achieve synchronization. It compares the contents of a memory location with a given value and, only if they are the same, modifies the contents of that memory location to a new given value. This is done as a single atomic operation. The atomicity guarantees that the new value is calculated based on up-to-date information; if the value had been updated by another thread in the meantime, the write would fail. The result of the operation must indicate whether it performed the substitution; this can be done either with a simple boolean response (this variant is often called compare-and-set), or by returning the value read from the memory location (not the value written to it).

CodePudding user response:

Yes, you can think about it that way. If the CAS succeeds, you are guaranteed that no other thread wrote to the memory location in between the "compare" and the "swap".

Some architectures simply lock that memory location (or cache line) during the operation so that other writes are impossible. On such architectures the CAS will always succeed. On other architectures (so-called LL/SC), the core doing the CAS may simply monitor the memory location, and if another write occurs at the wrong time, the CAS will not do its write and indicate failure instead.

  • Related