就C++标准而言(我猜是C++11和以后的版本,因为之前没有考虑线程),同时写入不同的、可能相邻的数组元素是否安全?
例如:
#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;
}
在这种情况下,语言是否保证数组不同元素的写入不会导致竞态条件?并且对于任何类型都有保证,还是有安全要求?