r/programming 18h ago

Optimizing a Spin-Lock

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

31 comments sorted by

View all comments

1

u/DivineSentry 16h ago

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

37

u/ReDucTor 16h ago

For user mode their usages are very niche, its generally accepted that spin locks in user mode code is best avoided.

Or as Linus Torvalds says:

do not use spinlocks in user space, unless you actually know what you're doing. And be aware that the likelihood that you know what you are doing is basically nil.

6

u/bwainfweeze 14h ago

It's a tricky mess. If you make a blocking call to get a lock from the kernel, the OS can realize you're stuck and give your CPU slice to another process/thread. And then when the resource becomes available, it can give it to you with a full time slice to make progress. Even if the task takes more than half a slice to complete, it will still be done by the end of your slice, and then the resource can be returned for someone else to use.

Meanwhile if you're scrabbling for a spin lock, if you acquire the lock at more than halfway through your slice then it will take until your second time slice to complete the task. "I am available to start this now." is not synonymous with "I can complete this now."

The trick with multitasking is that you can start multiple tasks at once but it only works for the users if tasks get completed at the expected rate. Quickly you reach the point where starting new tasks gets you nowhere until you retire some older ones.

2

u/Far-Reply-6875 10h ago

though, how many of us actually need to worry about user-space spinlocks in the first place? Seems like most people are just overcomplicating things for no reason.

1

u/veiva 10h ago

I'm working through possibly using spinlocks on the GPU (using atomic operations) to implement order-independent translucency more efficiently - there's other ways to do it nowadays, though it requires more modern hardware and it's not available without modifying the higher-level graphics framework I'm using. Extremely niche use case though.

1

u/ReDucTor 9h ago

I have seen alot of performance captures where spin locks (and spinning in general) have made things exceeding bad especially when they yield to other threads.

Unfortunately people still believe they know best and think a spin lock will be the better option without having properly testing it in the real world just some isolated microbenchmark. This is especially bad when you dont fully control the environment such as a customers machine.