As far as the C++ standard is concerned (C++11 and later, I guess, since before threads were not considered), is it safe to write concurrently to different, possibly adjacent, elements of an array?
For example:
#include <iostream>
#include <thread>
int array[10];
void func(int i) {
array[i] = 42;
}
int main()
{
for(int i = 0; i < 10; ++i) {
// spawn func(i) on a separate thread
// (e.g. with std::async, let me skip the details)
}
// join
for(int i = 0; i < 10; ++i) {
std::cout << array[i] << std::endl; // prints 42?
}
return 0;
}
In this case, is it guaranteed by the language that the writes of different elements of the array do not cause race conditions? And is it guaranteed for any type, or are there any requirements for this to be safe?