Reputation: 109
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:
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?
Upvotes: 2
Views: 347
Reputation: 155363
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.
Upvotes: 7