【问题标题】:std::for_each and unordered_map value modification with parallel execution policy使用并行执行策略修改 std::for_each 和 unordered_map 值
【发布时间】:2022-07-06 05:03:42
【问题描述】:

这种并行 for_each 的用法对 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;
}

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

【问题讨论】:

    标签: c++ multithreading parallel-processing c++17 thread-safety


    【解决方案1】:

    根据cppreference

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

    因此,那里的标准库没有(直接)帮助。

    但是,正如您自己指出的那样,这一行:

    my_map.at(d)=d+1.0;

    只是阅读地图。它唯一写入的是地图中的 elements,并且由于每个并行执行路径都将写入一个 不同 元素,这应该没问题。

    旁注:您的 lambda 不需要返回任何内容。

    【讨论】:

      猜你喜欢
      • 2020-02-04
      • 1970-01-01
      • 2021-07-23
      • 2021-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-06
      相关资源
      最近更新 更多