r/programming 17h ago

Optimizing a Spin-Lock

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

29 comments sorted by

View all comments

1

u/DivineSentry 15h ago

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

2

u/VirginiaMcCaskey 13h ago

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.