CPU X86 32位
文件:arch\x86\include\asm\cmpxchg_32.h
/* * Note: no "lock" prefix even on SMP: xchg always implies lock anyway. * Since this is generally used to protect other memory information, we * use "asm volatile" and "memory" clobbers to prevent gcc from moving * information around. */ #define __xchg(x, ptr, size) \ ({ \ __typeof(*(ptr)) __x = (x); \ switch (size) { \ case 1: \ { \ volatile u8 *__ptr = (volatile u8 *)(ptr); \ asm volatile("xchgb %0,%1" \ : "=q" (__x), "+m" (*__ptr) \ : "0" (__x) \ : "memory"); \ break; \ } \ case 2: \ { \ volatile u16 *__ptr = (volatile u16 *)(ptr); \ asm volatile("xchgw %0,%1" \ : "=r" (__x), "+m" (*__ptr) \ : "0" (__x) \ : "memory"); \ break; \ } \ case 4: \ { \ volatile u32 *__ptr = (volatile u32 *)(ptr); \ asm volatile("xchgl %0,%1" \ : "=r" (__x), "+m" (*__ptr) \ : "0" (__x) \ : "memory"); \ break; \ } \ default: \ __xchg_wrong_size(); \ } \ __x; \ }) #define xchg(ptr, v) \ __xchg((v), (ptr), sizeof(*ptr))
xchg是宏,不是真正的函数,该宏根据不同的字长调用不用的汇编指令操作。
举例:
int i = 10, j = 20;
xchg(&i, j); 返回值10;
//调用该宏后
i = 20, j = 20