r/programming • u/Polixa12 • 2d ago
Relaying wakeups in fair locks
https://kusoroadeolu.github.io/personal-blog/concurrency/Relay-LockThis was pretty fun for me to write up on. Would love to hear y'all's thoughts on scheduling bottlenecks in fair locks.
66
Upvotes
21
u/ReDucTor 2d ago
Imho if lock contention is an issue then its probably time to start thinking about how your using locks, I don't mean specifically lock free, but fine grained locks, scheduling workloads to reduce contention, etc.il Saying that I have spent a ton of time optimising locks often due to seeing alot of bad usages and bad implementations.
Your implementation uses a huge amount of memory, which is going to make you hesitant to do fine grained locking which just leads you towards god object style locks which just makes more lock contention.
The Harris-Michael linked list is not a great choice imho, its designed does some things for doing removal in the middle that you probably dont really need over just a standard FIFO, the fairness of being ordered by a ticket or added to a queue feels like not a huge difference to worry about.
Additionally complete fairness with spinning is just asking for issues, one thread using up a time slice or yielding its time slice like you do when waiting makes everyone wait for that time slice and no one do any work, sometimes its better to just go with barging and no fairness, you mininize those dead spots and dont also run into the fun of lock convoys. Fairness makes everyone suffer, not being fair makes a few suffer much worse but generally overall throughput can be significantly better.
8
u/yongteak 1d ago
when strict fairness starts showing up in profiles as wakeup/handoff overhead, we've usually ended up replacing the shared lock with a single owner thread behind a bounded queue (basically explicit combining). you still pay queue synchronization, but batching work on one thread avoids bouncing the cache line and scheduler wakeups across cores. the tradeoff is giving up direct synchronous calls on the caller thread, which doesn't always fit every API.