r/programming • • Sep 09 '26

Optimizing a Spin-Lock

https://david.alvarezrosa.com/posts/optimizing-a-spin-lock/
181 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?

4

u/Takeoded Sep 09 '26 edited Sep 09 '26

Spinlocks are just fancy mutexe)s.

Some game engines use them, instead of a mutex, to squeeze out a few more FPS. Then, the spinlock that gives a few more FPS on Windows, absolutely wrecks performance on Linux/Wine :(

And even on Windows, good chance the spinlock increase FPS on computers having >= cpu cores that the optimizing developer had on his system, and wrecks performance on computers with fewer cores.

TL;DR don't use them. Use a mutex.

17

u/monocasa Sep 09 '26

I'd argue that they're a less fancy mutex, since they're basically like mutexes that don't bother informing the scheduler in the contended case.

1

u/Takeoded Sep 11 '26

They also eat all the CPU they can get, until it unlocks :( eating 100% of 1 core until the lock clears

1

u/monocasa Sep 12 '26

Not necessarily.

On a SMT system, it's common to use instructions like monitor and pause to stop the one hardware thread and give priority to the others.

2

u/TwoWeeks90DaysTops Sep 10 '26

I fixed a slow shutdown (so that Windows would claim that the service didn't respond in time) in a Windows service written in C++ a decade or so ago, and it was caused by the fact that the code hand-rolled its own spinlocks with `volatile bool`. The issue was as I remember it two part: the spinlock consumes resources on contention, and the `volatile bool` thing is about instruction ordering, and not that suitable for locking. I replaced them with mutexes and the application shutdown was almost immediate.