Search code examples
cinline-assemblyspinlock

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


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.


Solution

  • 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