1

I know that Lock prefix in assembly creates a locked instruction that somehow similar to an atomic operation. But atomic operations in higher level languages normally have a memory ordering too (such as relaxed, released, and acquire memory ordering).

I wonder if these memory ordering will be translated into an assembly instruction or prefix too. Any idea?

Update: My question is about x86.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Afshin
  • 8,839
  • 1
  • 18
  • 53
  • What architecture are you programming for? This sounds a lot like x86 where the `lock` prefix iirc implies sequentially consistent ordering. – fuz Jul 10 '21 at 14:52
  • @fuz yes, I was asking for x86. but what happens if someone compiles its code with another memory ordering? – Afshin Jul 10 '21 at 15:02
  • 5
    https://stackoverflow.com/questions/38447226/atomicity-on-x86 might be helpful. The short, somewhat oversimplified description of memory ordering in x86 machine code is "ordinary loads are acquire, ordinary stores are release, the `lock` prefix provides sequential consistency". So for example C++'s `tmp = a.load(std::memory_order_acquire);` will compile into a simple `mov eax, [a]`. – Nate Eldredge Jul 10 '21 at 15:24
  • 1
    @Afshin In this case the memory ordering will be stricter than required by the program which is not generally a problem. – fuz Jul 10 '21 at 15:27
  • 1
    Related, possible duplicate: [Why does memory\_order\_relaxed use atomic (lock-prefixed) instructions on x86?](https://stackoverflow.com/q/24234769) - all atomic RMW operations on x86 are full barriers, so only compile-time ordering is possible even if you only write `fetch_add(mo_relaxed)` in your C++ source. Ah, found a previous answer of mine where I explained how C++ orders correspond to x86 asm, [Are memory orderings: consume, acq\_rel and seq\_cst ever needed on Intel x86?](https://stackoverflow.com/q/61719680) works as a dup I think. (And has links to more details for lots of stuff) – Peter Cordes Jul 10 '21 at 21:32

0 Answers0