Is there any simple way to improve performance of this spinlock function?

本小妞迷上赌 提交于 2019-12-06 10:13:07

问题


I'm trying to implement a spinlock in my code but the spinlock that I implemented based on Wikipedia results in extremely slow performance.

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");
}

Is there any way of improving this to make it faster?

Thanks.


回答1:


How about something like this (I understand this is the KeAcquireSpinLock implementation). My at&t assembly is weak unfortunately.

spin_lock:
    rep; nop
    test lockValue, 1
    jnz spin_lock
    lock bts lockValue
    jc spin_lock



回答2:


  "movl    $1,%%edx     \n\t"    // edx = 1;
  ".set    lockloop,.   \n\t"    // symbol lockloop set to pc
  "xorl    %%eax,%%eax  \n\t"    // eax = 0;
  "lock cmpxchgl %%edx,(%%ebx)\n\t" // if (*mu_ptr == eax) *mu_ptr = edx;
                                 //    else { eax = *mu_ptr;
  "jnz     lockloop     \n\t"    //           goto lockloop; }


来源:https://stackoverflow.com/questions/11923151/is-there-any-simple-way-to-improve-performance-of-this-spinlock-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!