Skip to content

Spinlock

A spinlock is a synchronization primitive that causes a thread trying to acquire it to wait in a loop ("spin") while repeatedly checking if the lock is available. Unlike mutexes that put threads to sleep, spinlocks keep threads active, making them suitable for very short critical sections. They are an important building block for low latency concurrent programming.

How Spinlocks Work

Spinlocks use an atomic boolean flag to represent the lock state:

  • false = unlocked (available)
  • true = locked (unavailable)

When a thread wants to acquire the lock, it tries to atomically change the flag from false to true. If successful, the thread has acquired the lock. If unsuccessful, the thread continues spinning until it succeeds.

When to Use Spinlocks

Use spinlocks when:

  • Critical sections are very short (< 1 microsecond)
  • Thread count is limited (≤ number of CPU cores)
  • You need predictable, low-latency synchronization
  • Context switching overhead is higher than spinning cost

Avoid spinlocks when:

  • Critical sections are long or unpredictable
  • You have many more threads than CPU cores
  • You need fairness guarantees
  • Power consumption is a concern

Your Task

Your task is to implement a spinlock class using everything you've learned so far. The spinlock should provide lock() and unlock() methods. The lock() method should spin until it successfully acquires the lock, and unlock() should release it.

Implement a spinlock class using std::atomic and compare_exchange_strong. The spinlock should provide lock() and unlock() methods. The lock() method should spin until it successfully acquires the lock, and unlock() should release it.

cpp
#include <atomic>

class Spinlock {
private:

    // Data structures here

public:
    // TODO: Implement lock() method
    // Should spin until the lock is successfully acquired
    // Use compare_exchange_strong to atomically change locked from false to true
    void lock() {
        // USER CODE HERE
    }

    // TODO: Implement unlock() method
    // Should release the lock by setting locked to false
    void unlock() {
        // USER CODE HERE
    }
};