首页 > 解决方案 > C ++ 17中数组索引范围的并行for循环

问题描述

我需要更新一个 100M 元素的数组,并希望并行执行。 std::for_each(std::execution::par, ...)这似乎很好,除了更新需要根据我正在更新的索引访问其他数组的元素。我试图并行化的那种东西的最小串行工作示例可能如下所示:

for (size_t i = 0; i < 100'000'000; i++)
    d[i] = combine(d[i], s[2*i], s[2*i+1]);

我当然可以手动生成线程,但这比 更多的代码std::for_each,所以很高兴找到一种优雅的方法来使用标准库执行此操作。到目前为止,我发现了一些不太优雅的使用方式for_each,例如:

有一个更好的方法吗?

标签: c++parallel-processingc++17

解决方案


std::ranges如果您可以访问 c++20,应该能够提供帮助,您可以迭代索引而不是数据:

#include <ranges>
#include <vector>
#include <algorithm>
#include <iostream>

int main() {
    std::vector<int> d(100);
    std::ranges::iota_view indexes((size_t)0, d.size());
    std::for_each(indexes.begin(), indexes.end(), [&d](size_t i)
    {
        std::cout << i << "," << d[i] << "\n";
    });
    return 0;
}

推荐阅读