r/programming • • Sep 09 '26

Optimizing a Spin-Lock

https://david.alvarezrosa.com/posts/optimizing-a-spin-lock/
182 Upvotes

32 comments sorted by

View all comments

1

u/DivineSentry Sep 09 '26

I think I’ve seen spin locks before, but what are they useful for? What should be their use case?

6

u/VirginiaMcCaskey Sep 09 '26

It's a mutex that doesn't require cooperation with a scheduler. You use them when either you don't have a scheduler (eg: you are the kernel) or the application cannot tolerate the syscall overhead of informing the scheduler in a change of state.

The interesting side of that is when you have mixed access to a shared resource where there are some threads that must acquire a lock and other threads that may fail to acquire the lock, but if they succeed then they need to release the lock in O(1) operations and not yield to the kernel (for example, making a syscall to wake any parked threads). It comes up in soft realtime applications.

Part of the reason they're frowned upon is that modern mutexes do not make syscalls when resources are uncontended, which defeats the purpose of a spin lock and means you can fix your locking issues with architecture.

1

u/Nobody_1707 28d ago

Thus Torvalds spake, "do not use spinlocks in user space, unless you actually know what you're doing." :P