最近看自旋锁的实现,自选锁的循环查找锁的主要实现相似以下,该实现使用到了内嵌的汇编(摘自sanos内核,源代码有2处实现,一处使用intel汇编,是没有问题的,另外一处使用内嵌汇编语法,源代码中为cmpxchgl %2, %0,是错误的,应该是cmpxchgl %0, %2)html
内嵌汇编有个固定格式,以下:ui
asm ( assembler template /* 汇编语句 */ : output operands /* 输出 */ : input operands /* 输入 */ : list of clobbered registers );
Compares the value in the AL, AX, EAX, or RAX register with the first operand (destination operand). If the twovalues are equal, the second operand (source operand) is loaded into the destination operand. Otherwise, thedestination operand is loaded into the AL, AX, EAX or RAX register. RAX register is available only in 64-bit mode.(* Accumulator = AL, AX, EAX, or RAX depending on whether a byte, word, doubleword, or quadword comparison is being performed *)
TEMP ← DEST
IF accumulator = TEMP
THEN
ZF ← 1;
DEST ← SRC;
ELSE
ZF ← 0;
accumulator ← TEMP;
DEST ← TEMP;
FI;
int atomic_compare_and_exchange(int *dest, int exchange, int comperand) { int old = comperand; if ( comperand== *dest) { *dest = exchange; } else { old = *dest; } return old; }
参考:http://blog.chinaunix.net/uid-23955580-id-2945814.htmlatom