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

0

u/ItsRSX Oct 05 '26 edited Oct 05 '26

Damn, that's almost enough babble to convince anybody you're a genius intellectual. Too bad every inch of you is dripping with disingenuous slime.

No, a read-side lock should never be more complex in terms of atomics, because every ISA you're dealing with has free acquire and free non-globally visible stores, allowing for basically free is locally acquired best-case checks and non-atomic increments under the average read case. Read/unlock is only marginally more expensive in that you have to compare against a zero writer wait list condition each time before either (a) fast path bailing out or (b) dispatching a semaphore or other form of wait list guarding the writer side.

No, there's isn't an essay worth of "variations" and "reader preferring", followed by "le sekret implications the masses wont understand". You're such a disingenuous hack that you know the navie approach would be reader preferring, with almost all real world applications considering that a bug open for writer starvation; so you rephased your entire babble implying a noob may end up coming across an edge case implementation in a totally not production ready library that's going to trip them up.

You know what actually would trip up the masses, though? Different recursive write-lock traits. Ordered vs nonordered wait queuing. A reenterant interface pathed to be writer-preferred-aware, blocking ReadToWrite upgrades indefinitely. There are so many valid concerns. Curious how you couldn't mention a single one of them. Curious how none of these are relevant to your babble about cache lines, nor do they carry any serious performance implications beyond carrying an extra word or so worth of wait count to be used against a split sideband waitlist queue thingy.

For pretty much all users, use cases, and product ready thread primitive libraries/os abis, the only real difference is "are you okay with 1-2 extra words (if that) for a faster average case" - we're talking less than or about as much astroturfed SSO overhead of strings or the oversized iterator pointers of a vector.

>"muh RCU lists" (which fun fact: are most likely going to suck because spamming cas and other such atomic ops stink worse than a higher level lock. not only do they perform worse in most cases, their limited implementation details end up being massive vectors for bugs, because youre pretty much stuck with 1 atomic pointer)
>"muh cache lines" (a performance grifers favourite buzzword)
>some babble about memory barriers despite working on strongly ordered platforms
>"hmm well achually, theres nuance i cannot properly describe with RW locks. the masses might get scared!!! theres your proof RW shouldnt be the default"
>"in summary, its actually not that big of a difference"
>"muh windows criticalsection is actually built around an nt kernel object instead of a futex" trivia
Aren't you a smart cookie? If you're going to waste that much time babbling just to pull platform specific trivia, at least make your whole post about how xyz stl has a sucky abi-locked thread primitive next time. You have about as much wisdom as a orange site headline.

1

u/ReDucTor Game Developer | quiz.cpp-perf.com Oct 11 '26 edited Oct 11 '26

Wow, that's probably the most toxic comment I have seen in a while, and full of incorrect information, poorly quoting the comment they are responding to. If you had any idea what you were talking about you probably would be posting actual evidence.

No, a read-side lock should never be more complex in terms of atomics

You have obviously never looked at the actual standard implementations like libc++ uses a complete unique locks every read lock/unlock or even https://godbolt.org/z/E69en4h6a

because every ISA you're dealing with has free acquire and free non-globally visible stores

What the hell are you on about? Looking at just x86 a load acquire and store release is generally free, however as soon as you get into something like fetch_add (lock xadd), exchange (xchg) or compare_exchange_* (lock cmpxchg) which all result in a lock that cause a full memory barrier so all loads and stores must complete prior to it's execution killing alot of opportunities for out of order execution.

there's isn't an essay worth of "variations" and "reader preferring", followed by "le sekret implications the masses wont understand". You're such a disingenuous hack that you know the navie approach would be reader preferring, with almost all real world applications considering that a bug open for writer starvation;

Go look at different implementations for example libstdc++ which uses pthread is read preferring while libc++ is write preferring but also depends on pthread_mutex waking order.

Will you be logging a bug for pthread's default mode being reader preferring and can cause writer starvation? Will you also call them names?

>"muh RCU lists" (which fun fact: are most likely going to suck because spamming cas and other such atomic ops stink worse than a higher level lock. not only do they perform worse in most cases, their limited implementation details end up being massive vectors for bugs, because youre pretty much stuck with 1 atomic pointer)

This is sad, you could not even be bothered to learn about RCU before making some weird as claim that it's going to be spamming CAS and other atomic operations for the reader.

RCU for the reader is basically (see the linux kernel)

(current_thread_tls->lock_count)++; // non atomic increment barrier();
// do work
barirer(); 
(current_thread_tls->lock_count)--; // non atomic decrement

>"muh cache lines" (a performance grifers favourite buzzword)

Anything where your constantly fighting over a cache line with a large amount of readers all sending request of ownership is going to hurt performance.

Use a reader writer lock, and solely readers and see the performance get destroyed

------------------------------------------------------------------
Benchmark                        Time             CPU   Iterations
------------------------------------------------------------------
SharedCompete/threads:1       27.3 ns         27.3 ns     25621216
SharedCompete/threads:2        194 ns          194 ns      3578536
SharedCompete/threads:4        383 ns          383 ns      1857556
NoOp/threads:1               0.529 ns        0.529 ns   1285870600
NoOp/threads:2               0.539 ns        0.539 ns   1302390726
NoOp/threads:4               0.598 ns        0.597 ns   1096311408
RCU/threads:1                0.868 ns        0.868 ns    806501759
RCU/threads:2                0.875 ns        0.875 ns    805791468
RCU/threads:4                0.892 ns        0.891 ns    787040868

>some babble about memory barriers despite working on strongly ordered platforms

I'm going to assume your talking x86 here, there is a difference between operations like mov [m32], r32 which you would get with atomic.store with memory_order_release or memory_order_relaxed compared with other operations like xchg [m32], r32 which you might see with an atomic.store with memory_order_seq_cst, with the xchg one having an implicit lock prefix ensuring that all prior reads and writes are completed. If you benchmark these two operations you will see there is a significant performance difference where some benchmarks you'll see up to 10x-20x performance difference.

>"in summary, its actually not that big of a difference"

Yes a shared_mutex exclusive lock and a mutex lock don't have a big difference with it only being about 2x in some benchmarks but if your looking at actual readers and comparing with something like RCU and scale up your threads in a benchmark RCU is going to end up 100x of times faster for solely readers because it usually doesn't use any of those "lock" instructions and when it does they are often on a the stack cache line when the barrier might be an std::atomic_thread_fence(std::memory_order_seq_cst) which will do things like lock or [rsp], 0.

Next time you decide to be a bit toxic, it might help to actually read up on what your claiming someone else does not know and do some actual testing, because you might find that the person your responding to has spent a lot of time working with a lot of concurrent code and given numerous talks relating to concurrency, including designing locks.

0

u/ItsRSX 16d ago edited 16d ago

Just a word of advice, if you want to be taken serious, try not to spend paragraphs upon paragraphs of babbling just for the punch line to be "nu-huh you don't know what a RCU is", "<godbolt link>", "muh pthreads", "muh libstd++", "ooo look linux kernel", "you wouldn't insult the glibc developers, now would you, HMMM", ""WOWZA look what happens if i use alignas here" between rather hallow and superficial statements.

You're clearly downstream from implementations and the work people like me have done for you. You're so beyond hope that cannot comprehend the fundamentals behind these primitives, instead electing to point in the vague direction of other implementations' you cannot comprehend, and asserting "hmm, well, i think this implementation does y. you wouldn't want to insult these lords amongst us - would you? all hail the notoriously amazing glibc."

I'm sorry you've spent so much time terminally online you think anybody owes you "evidence" to make a series of claims against obvious midwittery; and I'm sorry that you believe you're somehow proving a point by citing printfs between dogshit STL primitives whose opaque implementation you cannot see there, all using godbolt running on god knows what environment.

Sorry so called provider of "numerous talks relating to concurrency, including designing locks", that doesn't cut it. If you want my "evidence", you're going to have to put more effort in than pointing towards your printfs and STL usage linking against a platform specific crt. I will however take your claim at face value - only because it serves to prove my point about you being malicious in interpreting footguns that don't really exist by documenting patterns that should be avoided by platform vendors. Bonus points for my previous remark regarding your failure to cite the genuine pitfalls. This, much like the rest of your half-assed babble of citations to auxiliary projects, is very much on par for somebody who would brag about doing "numerous talks". You're all talk, all grift, and no bite. It's ashame you couldn't cite yourself articulating your point in a more proper and thought out form like you claim to have done "numerous" times over, as opposed to whatever the fuck that was.

Tell ya what, I'll leave this on a high note. If you respond again with another half-arsed benchmark after being calling out for falling performance grifter tropes (in this later case, the height of your claims seems to be spamming alignas around an opaque black hole of gunk, thinking you've somehow made a coherent point), I'll buy you a cookie.

1

u/ReDucTor Game Developer | quiz.cpp-perf.com 16d ago

You really need to seek mental help, your again coming back with unfounded dribble, expect to be taken seriously but clearly have no idea.

You're clearly downstream from implementations and the work people like me have done for you.

Based on your comments, I am going to assume your inability to understand when your in over your head, I am going to assume your commits to the documentation not actual code but sure show me the commits a major standard library lock implementation that you built.

When you come back with actual proof that anyone should take you seriously or come back with any sign of a technical argument that isn't easily debunked then I might take you slightly seriously.

Also your whole godbolt complaint thing, did you not think to take benchmarks out of compiler explorer run them locally? Which is what the results are from.