andersch.dev

<2025-04-20 Sun>

Spinlock

A spinlock is a synchronization primitive used in multithreading where a thread repeatedly checks a condition until it becomes available ("spinning").

Spinlocks cause CPU load (unlike mutexes) and block execution by actively spinning. However, they avoid the overhead of context switching, which makes them suitable for for brief waits or very short critical sections.

Code Example

typedef volatile int spinlock_t;

void spin_lock(spinlock_t *lock) {
    while (__sync_lock_test_and_set(lock, 1)) {
        // Spin until lock is acquired
    }
}

void spin_unlock(spinlock_t *lock) {
    __sync_lock_release(lock);
}