Disappointment of the day: compare_exchange_weak is useless in practice

⚓ rust    📅 2025-05-27    👤 surdeus    👁️ 4      

surdeus

Warning

This post was published 32 days ago. The information described in this article may have changed.

(This is a followup on this post)

compare_exchange_weak is advertised as:

function is allowed to spuriously fail even when the comparison succeeds, which can result in more efficient code on some platforms

My understanding was that "some platforms" here imply targets with LL/SC instructions which include ARM, PowerPC, and RISC-V. But in practice... there is absolutely on difference between compare_exchange_weak and compare_exchange on these targets.

Try changing one to another in this snippet: Compiler Explorer The generated assembly stays absolutely the same! I had hopes for RISC-V in this regard, but as you can see in this issue because of the (IMO) bonkers restriction in the ISA spec on retry loops used with LR/SC sequences, compilers (both LLVM and GCC) can not produce a more efficient code for compare_exchange_weak.

So if you want to optimize your atomic code, you may not bother with using compare_exchange_weak.

4 posts - 3 participants

Read full topic

🏷️ rust_feed