Fetch-and-add - X86 Implementation

X86 Implementation

In the x86 architecture, the instruction ADD with the destination operand specifying a memory location is a fetch-and-add instruction that has been there since the 8086 (it just wasn't called that then), and with the LOCK prefix, is atomic across multiple processors. However, it could not return the original value of the memory location (though it returned some flags) until the 486 introduced the XADD instruction.

The following is a C++ implementation for the GCC compiler, for both 32 and 64 bit x86 Intel platforms, based on extended asm syntax:

inline int fetch_and_add( int * variable, int value ){ asm volatile( "lock; xaddl %%eax, %2;" :"=a" (value) //Output : "a" (value), "m" (*variable) //Input :"memory" ); return value; }

Read more about this topic:  Fetch-and-add