Atomic behavior of unary increment operators

  • A+
Category:Languages

Somewhere I read that unary operators are atomic by nature and so they can be used as it is in multi threaded environment. To confirm the same, I wrote two separate programs where in

  1. I used a variable x and incremented using unary operator ++x
  2. I used a variable x and incremented using x=x+1

I compared the disassembly of both programs and found no difference. Please provide your inputs on this.

 


Somewhere I read that unary operators are atomic by nature and so they can be used as it is in multi threaded environment.

That source is completely wrong. You need to use std::atomic (or the C equivalent) to achieve atomicity – unary operations are not special.


I compared the disassembly of both programs and found no difference

That doesn't mean that the generated operations are atomic. There is no difference as any decent compiler will optimize x=x+1 and ++x into the same assembly (assuming built-in types).

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: