2

I have a simple spinlock implementation similar to this:

class Spinlock{
  std::atomic_flag flag;
public:
  Spinlock(): flag(ATOMIC_FLAG_INIT) {}
  ~Spinlock() {}

  void lock(){
    while(flag.test_and_set(std::memory_order_acquire));
  }

  void unlock(){
    flag.clear(std::memory_order_release);
  }
};

My question is similar to this one on mutexes but for spinlocks:

  • Thread 1 calls lock()
  • Before Thread 1 calls unlock(), Thread 2 and 3 both call lock().

Is it guaranteed that Thread 2 will acquire the spinlock before Thread 3?

If not, are there any lock implementations which guarantee the order of acquisition?

L.Koh
  • 109
  • 1
  • 8
  • No, they spin until they can grab it. This is the 'thundering herd'. – user207421 Apr 25 '19 at 05:32
  • If "order of acquisition" is a concern, then you should not be using a spin lock. Spin locks can be the highest-performing type of lock ***if*** the lock is uncontested, but they're the absolute worst when there is a lot of contention for the lock. Order of acquisition, on the other hand, is meaningless if the lock is uncontested: It only becomes a concern in the exact case where a spin lock would be the worst possible choice. – Solomon Slow Apr 25 '19 at 13:54

1 Answers1

7

No, there is no queuing or ordering of any kind, because plain spinlocks are really just repeated races; each time an attempt to acquire fails, there is no memory carried over to the next attempt, it's just racing and hoping to win. Thread 2 or 3 could acquire it, with roughly equal likelihood, even if Thread 2 had been spinning on it for a minute, and Thread 3 for a microsecond.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • Thanks for the clarification :) In that case are there any existing libraries with locks that guarantee order? – L.Koh Apr 25 '19 at 06:50
  • @L.Koh: I have no experience with any (spinlocks are typically for scenarios with ultra-high responsiveness requirements, where adding fairness guarantees defeats the purpose), but you can look up information on [ticket locks](https://en.wikipedia.org/wiki/Ticket_lock), which are what you get when you try to make a spinlock have guaranteed ordering. – ShadowRanger Apr 25 '19 at 10:19