0

Question in title. Is it?

Cause pre-increment just adds to the value, so I suppose it is only 1 instruction (not sure if that instruction takes a single cycle too, though).

Post-increment loads the value into a temporary copy, adds to it and then stores back.

Is pre-increment therefore atomic??

Haven't tried anything yet, just a question.

zeronull
  • 21
  • 2
  • 1
    I suppose the shortest answer is "no": it's a slight variation on the same steps as a post-increment – Rogue Nov 18 '22 at 17:15
  • 6
    Compiling to a single x86 instruction doesn't make it atomic, except on a uniprocessor machine or in a single-threaded process. Pre vs. post increment only compile differently if you use the result anyway, in which case you'll get `lock xadd` on an atomic type, otherwise just `lock add`. And if the type isn't atomic, the compiler will probably keep the value in a register unless that's all you're doing with it. Anyway, see the linked duplicate why why the answer is very much no, regardless of misconceptions about how it might compile (check https://godbolt.org/) – Peter Cordes Nov 18 '22 at 17:17
  • 1
    whether it is atomic in hardware is secondary when the language standard does not give that guarantee – 463035818_is_not_an_ai Nov 18 '22 at 17:19
  • 1
    As far as the C Standards are concerned, it is not only not atomic, it is sort of the opposite of atomic, in that `++i + ++i` is undefined. Not only is the update not tied to the access, it can be almost arbitrarily far removed from the access. – Steve Summit Nov 18 '22 at 18:57
  • Ultimately it depends on the hardware and the assembly code your compiler outputs. – puppydrum64 Nov 21 '22 at 18:05

0 Answers0