最近看自旋鎖的實現,自選鎖的循環查找鎖的主要實現相似以下,該實現使用到了內嵌的彙編(摘自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