Why do atomic operations like fetch-and-add return the old value of a mutable variable?

I'm trying to learn and better understand multithreading, but I hung up on the behavior of atomic functions like fetch-and-add. In the specific case of fetch-and-add, I understand that the value (let x, which is currently 5) is added to the increment value (say 3), the resulting sum (8) is written to x in memory, but the old value is returned (5).

There are several other such functions in different places (such as the atomic functions of OpenGL, Java AtomicIntegers, and many other areas) that behave this way. But I don’t understand why the place in the code wants to be written into memory and still return the value that it wants to change in the first place. Can anyone help shed some light on this?

+6
source share
3 answers

To expand the answer to Sergey’s question ...

I look at sampling and adding to be something like a semaphore; except the call "fetch and add" makes everything an atomic operation. The following is an example algorithm showing how to use the original value: http://research.omicsgroup.org/index.php/Ticket_lock

+2
source

The answer is very simple. The nature of atomic functions is that they change (increment in this case) the actual value at runtime , which may differ from the value that your code knew.

Example:

x = 5; // x is global y = atomically_increment(x); // what is y? 

Now, if x was changed from 5 to 6 before the increment actually happened, y will be 6 and from x to 9.

+3
source

Fetch-and-add instructions and operations (such as x86 XADD ) save you the trouble of running a CAS loop and providing the expected starting value.

However, this also means that in your code, after successfully successfully checking the selection and addition, you do not know what value was added in your addition and in a strong conflict, reading the value immediately before extracting and adding to it can still be far from the truth. Therefore, it is very useful to return the old or new value as a result of atomic sampling and addition.

As an example, Aeron uses the value returned by the fetch-and-add function to determine if it should rotate its buffer (see https://youtu.be/eKVpea51tvo?t=31m54s ).

+1
source

All Articles