*** Welcome to piglix ***

Fetch-and-add


In computer science, the fetch-and-add CPU instruction (FAA) atomically increments the contents of a memory location by a specified value.

That is, fetch-and-add performs the operation

in such a way that if this operation is executed by one process in a concurrent system, no other process will ever see an intermediate result.

Fetch-and-add can be used to implement concurrency control structures such as mutex locks and semaphores.

The motivation for having an atomic fetch-and-add is that operations that appear in programming languages as

are not safe in a concurrent system, where multiple processes or threads are running concurrently (either in a multi-processor system, or preemptively scheduled onto some single-core systems). The reason is that such an operation is actually implemented as multiple machine instructions:

When one process is doing x = x + a and another is doing x = x + b concurrently, there is a race condition. They might both fetch xold and operate on that, then both store their results with the effect that one overwrites the other and the stored value becomes either xold + a or xold + b, not xold + a + b as might be expected.

In uniprocessor systems with no kernel preemption supported, it is sufficient to disable interrupts before accessing a critical section. However, in multiprocessor systems (even with interrupts disabled) two or more processors could be attempting to access the same memory at the same time. The fetch-and-add instruction allows any processor to atomically increment a value in memory, preventing such multiple processor collisions.


...
Wikipedia

...