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
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
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.