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

后端 未结 16 1872
野性不改
野性不改 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:10

    AFAIK, According to the C++ standard, read/writes to an int are atomic.

    However, all that this does is get rid of the undefined behavior that's associated with a data race.

    But there still will be a data race if both threads try to increment i.

    Imagine the following scenario:

    Let i = 0 initially:

    Thread A reads the value from memory and stores in its own cache. Thread A increments the value by 1.

    Thread B reads the value from memory and stores in its own cache. Thread B increments the value by 1.

    If this is all a single thread you would get i = 2 in memory.

    But with both threads, each thread writes its changes and so Thread A writes i = 1 back to memory, and Thread B writes i = 1 to memory.

    It's well defined, there's no partial destruction or construction or any sort of tearing of an object, but it's still a data race.

    In order to atomically increment i you can use:

    std::atomic::fetch_add(1, std::memory_order_relaxed)

    Relaxed ordering can be used because we don't care where this operation takes place all we care about is that the increment operation is atomic.

提交回复
热议问题