Hacker News new | ask | show | jobs
by bheadmaster 1 day ago
> NOTE: Throughout our implementation we strictly use compare_exchange_strong, but the C++ standard suggests that for some systems like ARM it mighe be a better idea to run a loop with compare_exchange_weak for better performance. The problem with that is a compare_exchange_weak call may fail spuriously, which essentially it can randomly fail even if everything is correct, thus it makes code code a bit more complicated, so I avoided it for this implementation.

The reason using `compare_exchange_weak` is a better idea for lock-free algorithms is that, in most cases, you'll run it in a retry loop anyway. Since `compare_exchange_strong` is compiled to a retry loop, if you do a retry loop of `compare_exchange_strong` you basically have a loop in a loop. Using `compare_exchange_weak` makes things both simpler and more performant.

1 comments

This is overstated in value; on arm systems with LSE it's faster to use that even for weak operations than to use ll/sc. Even if you are limited to ll/sc the compiler may not put your cas-loop body into the ll/sc region as there's limitations on how many and what type of instructions are permitted there.
On ARM systems with LSE both weak and strong compile to the same CAS instruction anyway. On LL/SC, using strong means CPU will attempt to retry the same exchange on spurious failure, which increases likelihood that another thread will update the value in the meantime, requiring an outer loop retry.

On any plaform which implements strong exchange with zero overhead over weak exchange, we can safely assume they compile to the same thing, and use weak. The only reason to use `strong` is if you have a one-shot CAS operation and you don't want to write a retry loop.

Sure, with LSE. But you have to target LSE and get a system that actually contains it, i.e. not the default compiler flags and not the original AWS Graviton.