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

后端 未结 16 1869
野性不改
野性不改 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 11:01

    Never assume that an increment will compile down to an atomic operation. Use InterlockedIncrement or whatever similar functions exist on your target platform.

    Edit: I just looked up this specific question and increment on X86 is atomic on single processor systems, but not on multiprocessor systems. Using the lock prefix can make it atomic, but it's much more portable just to use InterlockedIncrement.

提交回复
热议问题