• Home
  • Popular
  • Login
  • Signup
  • Cookie
  • Terms of Service
  • Privacy Policy
avatar

Posted by John Dev


01 Dec, 2024

Updated at 14 Dec, 2024

What is the difference between `compare_exchange` with memory ordering and `compare_exchange` then `fence`

In the document of std::sync::atomic::fence, I see this code:

while self
    .flag
    .compare_exchange_weak(false, true, Ordering::Relaxed, Ordering::Relaxed)
    .is_err()
{}

fence(Ordering::Acquire);

Is it the same with this code below?

while self
    .flag
    .compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
    .is_err()
{}

Or, generally speaking, are these two expressions equivalent in all conditions?

atomic.compare_exchange/*_weak*/(current, new, success, failure)

vs

{
    let result = atomic.compare_exchange/*_weak*/(current, new, Ordering::Relaxed, Ordering::Relaxed);

    fence(if result.is_ok() { success } else { failure });

    result
}

1 post - 1 participant

Read full topic