簡單瞭解C語言內嵌彙編

最近看自旋鎖的實現,自選鎖的循環查找鎖的主要實現相似以下,該實現使用到了內嵌的彙編(摘自sanos內核,源代碼有2處實現,一處使用intel彙編,是沒有問題的,另外一處使用內嵌彙編語法,源代碼中爲cmpxchgl %2, %0,是錯誤的,應該是cmpxchgl %0, %2)html

內嵌彙編有個固定格式,以下:ui

asm ( assembler template         /* 彙編語句 */ : output operands /* 輸出 */ : input operands /* 輸入 */ : list of clobbered registers );
cmpxchgl的描述以下:
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;
  1. cmpxchgl %0, %2爲彙編語句,表示對第3個和第1個入參進行操做,即cmpxchgl *dest,exchange;
  2. "=m" (*dest), "=a" (old)爲輸出部分,將m內存的內容存到*dest中,將a寄存器內容存到old;
  3. "r" (exchange), "m" (*dest), "a" (comperand)); 爲輸入部分,將exchange放入r寄存器,將*dest放入m,將comperand放入a寄存器;
使用C語言翻譯以下:
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

相關文章
相關標籤/搜索