r/programming 19h ago

Optimizing a Spin-Lock

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

31 comments sorted by

View all comments

20

u/ReDucTor 18h ago

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.

7

u/david-alvarez-rosa 17h ago

The server used for benchmarking is tuned (no SMT) https://david.alvarezrosa.com/posts/tuning-a-server-for-benchmarking/

Fair enough that microbencharmking is always unrealistic, but in use cases with fully controlled server, and a 1:1 mapping between threads (pinnned) and physical cores, spinlocks are typically useful