C ++ 17中数组索引范围的并行for循环 [英] Parallel for loop over range of array indices in C++17

查看:115
本文介绍了C ++ 17中数组索引范围的并行for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要更新一个100M元素的数组,并希望并行执行. std :: for_each(std :: execution :: par,...)似乎很不错,只是根据我要更新的索引,更新需要访问其他数组的元素.我尝试并行化的一种最小的 serial 工作示例可能看起来像这样:

I need to update a 100M-element array and would like to do it in parallel. std::for_each(std::execution::par, ...) seems great for this, except that the update needs to access elements of other arrays depending on the index that I am updating. A minimal serial working example of the kind of thing I'm trying to parallelize might look like this:

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 的方法不是很优雅,例如:

I could of course manually spawn threads, but that is a lot more code than std::for_each, so it would be great to find an elegant way to do this with the standard library. So far I have found some not very elegant ways of using for_each, for instance:

  • 通过对数组元素的地址使用指针算法来计算索引.

  • Compute the index by using pointer arithmetic on the address of the array element.

本着boost的 counting_range 的精神实现我自己的虚假迭代器.

Implement my own bogus iterator in the spirit of boost's counting_range.

有更好的方法吗?

推荐答案

std :: ranges 应该能够提供帮助,您可以遍历索引而不是比您的数据

std::ranges should be able to help if you have access to c++20, you can iterate over the indexes rather than your data:

#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;
}

这篇关于C ++ 17中数组索引范围的并行for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆