r/programming • u/david-alvarez-rosa • Sep 09 '26
Optimizing a Spin-Lock
https://david.alvarezrosa.com/posts/optimizing-a-spin-lock/
183
Upvotes
r/programming • u/david-alvarez-rosa • Sep 09 '26
4
u/Raknarg Sep 09 '26
pretty cool. Learned a few things from this.
28
u/ReDucTor Sep 09 '26
What CPU are you using? Does it have SMT? If so your pinning might be using sibling cores for some threads.
With the benchmark its unrealistic your essentially forcing extreme lock contention and then forcing different threads to wait for longer to reduce lock contention and cache coherence contention. Sadly this is measuring the average without showing the worst case or standard deviation for the threads that are starved from accessing the lock.
Also the workload plays a significant part, you only have a single addition that is forced to not share a cache line (might not help some CPUs that always hw prefetch subsequent cache lines). In the real world your lock will likely do more, otherwise if it was this simple you would just atomic fetch add, or even CAS loop.
The pause should probably mentjon that its sort of acting like serializing instruction reducing the branch misses as it won't speculatively execute a bunch of loads to the lock variable check if it's locked before it has the previous result.
The blog post should be putting significantly more emphasis on dont use spin locks in user mode. I have seen way to many profile captures of a spin locks killing performance.
43
u/Takeoded Sep 09 '26
Spinlock performance can change drastically between kernel versions, and between schedulers (eg CFS vs EEVDF vs SCX-LAVD), which kernel and scheduler were you benchmarking on?
Also, please add a comparison to a boring old std::mutex into your benchmarks. Call it V0
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?
1
u/3inthecorner Sep 10 '26
What unit is the energy for? A single increment or a whole benchmark run? How many increments per run?
-13
u/AryanPandey Sep 09 '26
It's great, but in cpp, i learnt stuff in c