I've heard i++ isn't thread safe, is ++i thread-safe?

后端 未结 16 1839
野性不改
野性不改 2020-11-27 10:38

I\'ve heard that i++ isn\'t a thread-safe statement since in assembly it reduces down to storing the original value as a temp somewhere, incrementing it, and then replacing

16条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 11:18

    I think that if the expression "i++" is the only in a statement, it's equivalent to "++i", the compiler is smart enough to not keep a temporal value, etc. So if you can use them interchangeably (otherwise you won't be asking which one to use), it doesn't matter whichever you use as they're almost the same (except for aesthetics).

    Anyway, even if the increment operator is atomic, that doesn't guarantee that the rest of the computation will be consistent if you don't use the correct locks.

    If you want to experiment by yourself, write a program where N threads increment concurrently a shared variable M times each... if the value is less than N*M, then some increment was overwritten. Try it with both preincrement and postincrement and tell us ;-)

提交回复
热议问题