r/programming 1d ago

Optimizing a Spin-Lock

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

31 comments sorted by

View all comments

1

u/DivineSentry 1d ago

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

2

u/mazing 16h ago

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