【发布时间】: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