r/programming • • Sep 09 '26

Optimizing a Spin-Lock

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

32 comments sorted by

View all comments

Show parent comment

2

u/mazing Sep 10 '26

I guess it's not truly a spinlock, but closely related is "busy waiting", which is sometimes very useful for realtime programs.

For example, I want consistent 16ms between my game engine server frames.

Using sleep(time-to-next-frame) throws control back to the OS. But windows bundles these and you might request 3ms sleep and get 15ms. (windows is doing 64hz from what I can tell)

So in this case I'll check how much time I have to next frame, if it's more than the measured sleep precision then I sleep. Rest of the time is spinlock/busy waiting.

Eats CPU but the frames land like clockwork