最近看自旋鎖的實現,自選鎖的迴圈查找鎖的主要實現類似如下,該實現使用到了內嵌的彙編(摘自sanos內核,源代碼有2處實現,一處使用intel彙編,是沒有問題的,另一處使用內嵌彙編語法,源代碼中為cmpxchgl %2, %0,是錯誤的,應該是cmpxchgl %0, %2) 內嵌彙編有個固定格式,如 ...
最近看自旋鎖的實現,自選鎖的迴圈查找鎖的主要實現類似如下,該實現使用到了內嵌的彙編(摘自sanos內核,源代碼有2處實現,一處使用intel彙編,是沒有問題的,另一處使用內嵌彙編語法,源代碼中為cmpxchgl %2, %0,是錯誤的,應該是cmpxchgl %0, %2)
內嵌彙編有個固定格式,如下:
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;
- cmpxchgl %0, %2為彙編語句,表示對第3個和第1個入參進行操作,即cmpxchgl *dest,exchange;
- "=m" (*dest), "=a" (old)為輸出部分,將m記憶體的內容存到*dest中,將a寄存器內容存到old;
- "r" (exchange), "m" (*dest), "a" (comperand)); 為輸入部分,將exchange放入r寄存器,將*dest放入m,將comperand放入a寄存器;
參考:http://blog.chinaunix.net/uid-23955580-id-2945814.html