Search code examples
cpumutexspinlocklocks

When is a good idea to use a spinlock?


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?


Solution

  • 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.