有没有简单的方法可以提高此自旋锁功能的性能?

Jig*_*uff 2 c inline-assembly spinlock

我正在尝试在我的代码中实现一个自旋锁,但是我基于Wikipedia实现的自旋锁导致了极慢的性能.

int lockValue = 0;

void lock() {
    __asm__("loop: \n\t"
            "movl $1, %eax \n\t"
            "xchg %eax, lockValue \n\t"
            "test %eax, %eax \n\t"
            "jnz loop");
}
Run Code Online (Sandbox Code Playgroud)

有没有办法改善这一点,使其更快?

谢谢.

cni*_*tar 5

这样的事情怎么样(我明白这是KeAcquireSpinLock实现).不幸的是,我的at&t大会很弱.

spin_lock:
    rep; nop
    test lockValue, 1
    jnz spin_lock
    lock bts lockValue
    jc spin_lock
Run Code Online (Sandbox Code Playgroud)

  • 另见:[什么是"代表; nop;" 在x86汇编中意味着什么?](http://stackoverflow.com/questions/7086220/what-does-rep-nop-mean-in-x86-assembly)和[x86暂停指令如何在spinlock中工作并且可以使用它在其他情况下?](http://stackoverflow.com/questions/4725676/how-does-x86-pause-instruction-work-in-spinlock-and-can-it-be-used-in-other-sc) (2认同)
  • 另请参阅:[x86汇编中"锁定"指令的含义是什么?](http://stackoverflow.com/questions/8891067/what-does-the-lock-instruction-mean-in-x86-assembly)和[多核CPU上的x86 LOCK](http://stackoverflow.com/questions/3339141/x86-lock-question-on-multi-core-cpus/3339380#3339380)和[单核/多核上的原子操作] ](http://wiki.osdev.org/Atomic_operation) (2认同)