r/cpp • • Sep 04 '26

Optimizing a Spin-Lock

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

31 comments sorted by

View all comments

Show parent comment

6

u/ReDucTor Game Developer | quiz.cpp-perf.com Sep 05 '26

sched_yield is yet another terrible approach, its forcing the surrendering of the time slice and no way for the lock holder to wake you. Most people use spin locks because they believe their critical section is really small and that a mutex will have too much overhead because of the potential syscalls and OS overhead, sched_yield gives you the syscall overhead and even more.

For the time tracking and waiter count you will end up with more cache traffic under heavy contention and a larger lock. Using a full ticket based lock can also lead to lock convoys, especially if you dont allow barging, while a ticket makes it fair it means that under contention every thread end up waiting even when another thread is not in the critical section yet because its still waking up. 

Using a parking lot based mutex is normally better in all situations, it can do adaptive spinning on a different cache line to the lock holder and actually wake up the other thread, however the spin lock often used for the bucket lock potentially brings back all of the issues with yielding.

3

u/Fabulous-Meaning-966 Sep 05 '26

Yes, I have the same reservation about spinlocks guarding a lock's wait list, but I think the requirement there is just to avoid disaster under very rare conditions (since the critical section is a few ns), which means falling back to sched_yield() is probably fine.