1

About swap(), docs say that: "using Acquire makes the store part of this operation Relaxed".

I understand this as:

let atom = AtomicBool::new(true);
let prev = atom.swap(false, Ordering::Acquire);
print!("hello");

is equivalent to:

let atom = AtomicBool::new(true);
let prev = atom.load(Ordering::Acquire);
atom.store(false, Ordering::Relaxed);
print!("hello");

which compiler can then rearrange to:

let atom = AtomicBool::new(true);
let prev = atom.load(Ordering::Acquire);
print!("hello");
atom.store(false, Ordering::Relaxed);

Is this correct? If yes, will "SeqCst" ordering also result in equivalent load, store separated with potential interleaving in between?

4
  • 2
    The compiler can't rearrange atomic operations since they consist of a single asm instruction on most platforms, but the CPU can proceed to the print without waiting for the store to be visible on other cores. As for SeqCst, the docs state that it is more or less equivalent to AcqRel for load-with-store operations (i.e. swap). Commented Jan 19, 2024 at 7:41
  • "the CPU can proceed to the print without waiting for the store to be visible on other cores." AcqRel should avoid that right? Commented Jan 19, 2024 at 8:23
  • Actually, AcqRel won't avoid it now that i think about it. Thanks. Commented Jan 19, 2024 at 8:30
  • See For purposes of ordering, is atomic read-modify-write one operation or two? - the store can indeed reorder with later operations on other objects, but the load+store are still an atomic RMW on the cache line containing the object you're modifying. Unlike your second code block. Atomic RMWs are linearizable (so e.g. atomic increments don't lose counts), separate load + separate store aren't. Is incrementing an int effectively atomic in specific cases? Commented Jan 19, 2024 at 13:57

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.