問題描述
我在 Qt 的源代碼中看到了一些 x86 程序集:
I saw some x86 assembly in Qt's source:
q_atomic_increment:
movl 4(%esp), %ecx
lock
incl (%ecx)
mov $0,%eax
setne %al
ret
.align 4,0x90
.type q_atomic_increment,@function
.size q_atomic_increment,.-q_atomic_increment
通過谷歌搜索,我知道
lock
指令會導致CPU鎖定總線,但我不知道CPU何時釋放總線?
From Googling, I knew
lock
instruction will cause CPU to lock the bus, but I don't know when CPU frees the bus?
關于上面的整個代碼,我不明白這段代碼是如何實現Add
的?
About the whole above code, I don't understand how this code implements the Add
?
推薦答案
LOCK
本身不是一條指令:它是一個指令前綴,適用于后面的指令.該指令必須是對內存(INC
、XCHG
、CMPXCHG
等)執行讀-修改-寫操作的指令——在此如果是incl (%ecx)
指令,inc
將l
ong 字修改為ecx中保存的地址代碼>注冊.
LOCK
is not an instruction itself: it is an instruction prefix, which applies to the following instruction. That instruction must be something that does a read-modify-write on memory (INC
,XCHG
,CMPXCHG
etc.) --- in this case it is theincl (%ecx)
instruction whichinc
rements thel
ong word at the address held in theecx
register.
LOCK
前綴確保 CPU 在操作期間擁有適當緩存行的獨占所有權,并提供某些額外的排序保證.這可以通過斷言總線鎖定來實現,但 CPU 將在可能的情況下避免這種情況.如果總線被鎖定,那么它只是在鎖定指令的持續時間內.
The LOCK
prefix ensures that the CPU has exclusive ownership of the appropriate cache line for the duration of the operation, and provides certain additional ordering guarantees. This may be achieved by asserting a bus lock, but the CPU will avoid this where possible. If the bus is locked then it is only for the duration of the locked instruction.
這段代碼將要遞增的變量的地址從堆棧復制到ecx
寄存器中,然后它以原子方式執行lock incl (%ecx)
將該變量加 1.如果變量的新值為 0,則接下來的兩條指令將 eax
寄存器(保存函數的返回值)設置為 0,否則設置為 1.該操作是一個增量,而不是一個添加(因此得名).
This code copies the address of the variable to be incremented off the stack into the ecx
register, then it does lock incl (%ecx)
to atomically increment that variable by 1. The next two instructions set the eax
register (which holds the return value from the function) to 0 if the new value of the variable is 0, and 1 otherwise. The operation is an increment, not an add (hence the name).
這篇關于“鎖"有什么作用?x86匯編中的指令是什么意思?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!