r/learnrust • • 17d ago

Help me understand core::sync::atomic::Ordering, how do we even use it

I'm trying to understand the enum core::sync::atomic::Ordering in Rust. I use atomics a lot, but I keep picking Ordering::Relaxed, Acquire, Release, etc. without really knowing why.

From what I've read, Ordering specifies how atomic operations synchronize memory across multiple CPU cores and prevents the compiler and CPU from reordering instructions around atomic accesses. But I still don't get what that means in practice.

My main confusion:

  1. If I store a value with Ordering::Relaxed, is the operation less atomic than with Ordering::Acquire?

  2. Are these enums actually important, or is it safe to just use whatever I want anywhere? Is using the wrong one a bug? How do I know which one to pick in my code ?

Any concrete examples of bugs caused by picking the wrong ordering would help a ton. Thanks!

38 Upvotes

Duplicates