“锁"有什么作用?x86汇编中的指令是什么意思?

2021-12-09 00:00:00 qt assembly c++ x86

我在 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

  1. 通过谷歌搜索,我知道lock指令会导致CPU锁定总线,但我不知道CPU何时释放总线?

  1. 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?

推荐答案

  1. LOCK 本身不是一条指令:它是一个指令前缀,适用于后面的指令.该指令必须是对内存(INCXCHGCMPXCHG 等)执行读-修改-写操作的指令――在此如果是 incl (%ecx) 指令,inclong 字修改为 ecx注册.

  1. 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 the incl (%ecx) instruction which increments the long word at the address held in the ecx 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).

相关文章