Spinlocks, How Useful Are They?

Viewed 25929

How often do you find yourself actually using spinlocks in your code? How common is it to come across a situation where using a busy loop actually outperforms the usage of locks?
Personally, when I write some sort of code that requires thread safety, I tend to benchmark it with different synchronization primitives, and as far as it goes, it seems like using locks gives better performance than using spinlocks. No matter for how little time I actually hold the lock, the amount of contention I receive when using spinlocks is far greater than the amount I get from using locks (of course, I run my tests on a multiprocessor machine).

I realize that it's more likely to come across a spinlock in "low-level" code, but I'm interested to know whether you find it useful in even a more high-level kind of programming?

10 Answers

Always keep these points in your mind while using spinlocks:

  • Fast user mode execution.
  • Synchronizes threads within a single process, or multiple processes if in shared memory.
  • Does not return until the object is owned.
  • Does not support recursion.
  • Consumes 100% of CPU while "waiting".

I have personally seen so many deadlocks just because someone thought it will be a good idea to use spinlock.

Be very very careful while using spinlocks

(I can't emphasize this enough).

Related