Does this usage of parallel for_each is ok with unordered_map:
void test()
{
std::vector<double> vec;
constexpr auto N = 1000000;
for(auto i=0;i<N;i ) // this is just for the example purpose
vec.push_back(i*1.0);
auto my_map = std::unordered_map<double,double>();
for(const auto d: vec)
my_map.try_emplace(d,d); // I prefill the map with some elements
// Here i use par_unseq but just modify the value not the key, so just individual elements of the map
std::for_each(std::execution::par_unseq,vec.cbegin(),vec.cend(),[&](double d) { return my_map.at(d)=d 1.0;});
auto total=0.0;
for(const auto [key,value]: my_map)
total =value;
std::cout << total << std::endl;
}
I first fill the unordered_map with empty elements and then just modify each individual elements. All my tests are successful but I dont know if its just luck or not.
CodePudding user response:
According to cppreference:
When using parallel execution policy, it is the programmer's responsibility to avoid data races and deadlocks
So, no (direct) help from the Standard Library there.
However, as you yourself point put, this line:
my_map.at(d)=d 1.0;
is only reading the map. The only thing it's writing to is the elements (by which I mean values) in the map, and since each parallel path of execution will be writing to a different element, this should be OK.
Sidenote: your lambda doesn't need to return anything.