When is a good idea to use a spinlock?

3.1k views Asked by At

It seems that spinlocks aren't that great as they waste CPU cycles when the are waiting (blocking). If the thread just goes to sleep while waiting for a signal to wakeup, then CPU cycles aren't lost while spinning.

Maybe it is good to use a spinlock if the locks are held for a very short time, then maybe it uses less time? If this is true why?

3

There are 3 answers

0
LukeH On BEST ANSWER

Yes, that's correct.

Because context switches are expensive. The OS and CPU have to do a (relatively) large amount of work to perform a context switch. Spinning for a few cycles instead will be a lot cheaper, even if those cycles are, in theory, wasted.

0
Chris Pitman On

Spinlocks are faster when they do not block, which is why they are useful in situations where there is very low contention in the lock (ie a very low chance it is already locked).

When a thread sleeps it cause a context switch (ie, this thread gets swapped out for another so that the other thread may run). There is also usually higher overhead to acquiring a standard mutex than there is for checking if a spinlock is free. Very often spinlocks only require a single atomic operation when the lock is free.

These properties make spinlocks useful for fine grained locking, since using smaller locks decreases the contention on each lock. For example, one of my projects has a map with ~200,000 entries being accessed by 16+ threads at the same time (enterprise server type of thing). Having a spinlock per entry is fairly efficient because the chance that two threads in this app try to hit the same entry at the same time is low.

1
Aater Suleman On

Spinlocks allow for tight polling and faster wakeups when lock becomes available. They are also good for non-contended locks as @Chris pointed out. I would say use spin locks:

  1. If all you care about is performance of your own application, and don't want to yield to the other apps and your app has <= threads than the number of cores. I would still consider ticket locks to optimize for cache misses however... they also spin but reduce cache misses a lot.

  2. or, if your locks are less contended