How do compare_exchange_weak and compare_exchange_strong differ, and when should each be used?
Show answer and explanation
Both operations compare an atomic value with expected, store the desired value on success, and replace expected with the observed value on failure. The weak form may also fail spuriously, so it is normally used in a loop that must retry after any mismatch and can be cheaper on some targets. The strong form avoids spurious failure and suits a one-shot decision or code where rebuilding the desired value is expensive, though real contention can still make it fail. Success and failure memory orders must be valid for their respective paths; the failure order cannot perform a release operation.
Both operations compare an atomic value with expected, store the desired value on success, and replace expected with the observed value on failure. The weak form may also fail spuriously, so it is normally used in a loop that must retry after any mismatch and can be cheaper on some targets. The strong form avoids spurious failure and suits a one-shot decision or code where rebuilding the desired value is expensive, though real contention can still make it fail. Success and failure memory orders must be valid for their respective paths; the failure order cannot perform a release operation.
Connect the conclusion directly to the type, lifetime, ownership, overload-resolution rule, or library contract present in the question. State implementation dependence or a violated precondition explicitly instead of merely guessing output.