Skip to content
Search

SpinLock

lastmod 2018-08-17created 2015-03-0713 edits

A spinlock is a lock implemented so that, when entering the critical section is not possible, it keeps retrying in a loop until entry becomes possible. The name spinlock means that the thread keeps spinning around until it acquires the lock. A spinlock is a kind of busy waiting.

Because a spinlock does not rely on the operating system's scheduling support, no context switch occurs for that thread. Therefore a spinlock is efficient when the critical section can be entered within a short time, since it eliminates the context switch. However, if the spinlock takes a long time, other threads cannot run and must wait, which leads to inefficient results.

Developed with the concept "If it'll be usable right after a short wait, why bother adding load with a context switch?", it means that when entering the critical section is not possible, instead of doing a context switch, the thread loops for a while and retries.

Implementation

#include <boost/atomic.hpp>

class spinlock {
private:
  typedef enum {Locked, Unlocked} LockState;
  boost::atomic<LockState> state_;

public:
  spinlock() : state_(Unlocked) {}

  void lock()
  {
    while (state_.exchange(Locked, boost::memory_order_acquire) == Locked) {
      /* busy-wait */
    }
  }
  void unlock()
  {
    state_.store(Unlocked, boost::memory_order_release);
  }
};

See also

Favorite site

References


  1. Spinlocks_and_Read-Write_Locks.pdf ↩