What is a spinlock?

Answer

A spinlock is a synchronization mechanism where a thread repeatedly checks ("spins") in a loop until the lock becomes available, rather than sleeping and being woken up. It's a busy-wait lock. Implementation: // Simple spinlock (hardware atomic instruction): struct spinlock { atomic_flag locked = ATOMIC_FLAG_INIT; }; void spin_lock(spinlock* lock) { while (atomic_flag_test_and_set(&lock->locked)) { // Spin -- keep looping until lock is free! } } void spin_unlock(spinlock* lock) { atomic_flag_clear(&lock->locked); } // Usage: spin_lock(&lock); // Critical section spin_unlock(&lock);. Compare-and-Swap (CAS) based: bool compare_and_swap(int* addr, int expected, int desired); void spin_lock(int* lock) { while (!compare_and_swap(lock, 0, 1)) { /* spin */ } }. Advantages over sleeping mutex: no context switch overhead; no scheduler involvement; very fast when lock held for VERY short time (fewer nanoseconds than a context switch). Disadvantages: wastes CPU cycles (spinning = doing nothing useful); bad when lock held for long time or many threads waiting; on single-core → spinning is useless (the holder can't make progress); can cause priority inversion; battery waste on mobile devices. When to use spinlocks: multiprocessor systems only; lock held for fewer microseconds; interrupt context (can't sleep in interrupt handler). Ticket spinlock / MCS lock: fair spinlocks — threads wait in order, preventing starvation. Used in Linux kernel. Adaptive locks: spin briefly then sleep if still locked — best of both worlds. Java synchronized, Linux futex use adaptive approaches.