std::for_each和unordered_map值修改并行执行策略



对于unordered_map:

是否可以使用parallel for_each:
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;
}

我首先用空元素填充unordered_map,然后修改每个单独的元素。我所有的测试都成功了,但我不知道是不是运气好。

根据cppreference:

当使用并行执行策略时,程序员有责任避免数据竞争和死锁

所以,没有(直接)来自标准库的帮助。

然而,正如你自己所指出的,这一行:

my_map.at(d)=d+1.0;

只是读取地图。它写入的唯一对象是映射中的元素(我指的是值),由于每个并行执行路径都将写入不同的

元素,因此这应该是可以的。旁注:你的lambda不需要返回任何东西。

最新更新