In software engineering, a spinlock is a lock where the thread simply waits in a loop ("spins") repeatedly checking until the lock becomes available.
The following example uses x86 assembly language to implement a spinlock. It will work on any Intel 80386 compatible processor.
# Intel syntax
lock: # The lock variable. 1 = locked, 0 = unlocked.
dd 0
spin_lock:
mov eax, 1 # Set the EAX register to 1.
loop:
xchg eax, [lock] # Atomically swap the EAX register with
# the lock variable.
# This will always store 1 to the lock, leaving
# previous value in the EAX register.
test eax, eax # Test EAX with itself. Among other things, this will
# set the processor's Zero Flag if EAX is 0.
# If EAX is 0, then the lock was unlocked and
# we just locked it.
# Otherwise, EAX is 1 and we didn't acquire the lock.
jnz loop # Jump back to the XCHG instruction if the Zero Flag is
# not set, the lock was locked, and we need to spin.
ret # The lock has been acquired, return to the calling
# function.
spin_unlock:
mov eax, 0 # Set the EAX register to 0.
xchg eax, [lock] # Atomically swap the EAX register with
# the lock variable.
ret # The lock has been released.