Replacing the atomic_add Instruction
This function is used to perform atomic addition on integer variables.
- Code on x86:
static inline void atomic_add(int i, atomic_t *v) { asm volatile(LOCK_PREFIX "addl %1,%0" : "+m" (v->counter) : "ir" (i));// Add i to the atomic variable v->counter. } - Alternatives for Kunpeng processors:
Method 1: Use the built-in atomic operations provided by the GUN compiler collection (GCC).
__sync_add_and_fetch(&_value.counter,1)
Method 2: Use the inline assembly.
void atomic_add (int i) { unsigned int tmp; int result; __asm__ volatile(" prfm pstl1strm, %2\n" "1: ldaxr %w0, %2\n" // Load data to the register. " add %w0, %w0, %w3\n" // Perform an add operation. " stlxr %w1, %w0, %2\n" // Write data after the add operation to the memory and check whether the data is successfully written. "cbnz %w1, 1b" // If the preceding operation fails, perform the add operation again. : "=&r"(result), "=&r"(tmp), "+Q"(_value.counter) : "Ir"(i)) }
Parent topic: Source Code Modification Cases