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

What does the quot;lockquot; instruction mean in x86 assembly?(“锁有什么作用?x86汇编中的指令是什么意思?)
本文介绍了“锁"有什么作用?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).

这篇关于“锁"有什么作用?x86汇编中的指令是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Is it possible to connect a signal to a static slot without a receiver instance?(是否可以在没有接收器实例的情况下将信号连接到静态插槽?)
how to restart my own qt application?(如何重新启动我自己的 qt 应用程序?)
Where in Qt Creator do I pass arguments to a compiler?(在 Qt Creator 中,我在哪里将参数传递给编译器?)
Using a Qt-based DLL in a non-Qt application(在非 Qt 应用程序中使用基于 Qt 的 DLL)
Configuring the GCC compiler switches in Qt, QtCreator, and QMake(在 Qt、QtCreator 和 QMake 中配置 GCC 编译器开关)
Difference between creating object with () or without(使用 () 或不使用 () 创建对象的区别)