- In android, cmpxchg performs atomic operations, such as auto-addition and auto-subtraction.
- Cmpxchg exists in 486 and more advanced CPUs. Other types of CPUs, such as Arm, do not have this command.
Cmpxchg commands are encapsulated in Functionsandroid_atomic_cmpxchg
The function is located in atomic. c and is preprocessed.
#elif defined(__i386__) || defined(__x86_64__)
Protected.
1. source code analysis:
The reference link of the annotation is:
- Gnu asm template syntax
- Lock
- Cmpxchg instruction
- Setne
Therefore, the function is used:If oldvalue = * addr, The newvalue is assigned to * addr, and 1 is returned. Otherwise, 0 is returned..
(1 indicates that the new value has been assigned to the variable/register, and 0 indicates that no value is assigned)
Example 2: 2.1 oldval = newval
int32_t a = 5;int b = android_atomic_cmpxchg( a, a+1, &a );printf("%d, %d\n", a, b);
The result is:
6, 1
2.2 oldval! = Newval
int32_t a = 5;int b= android_atomic_cmpxchg( a, a, &a );printf("%d, %d\n", a, b);
The result is:
5, 0
3 Reference
Other functions suchandroid_atomic_inc
,android_atomic_dec
And so on.android_atomic_cmpxchg
To implement these functions.atomic.c
Medium