简体   繁体   English

OpenMP 任意缩减(合并)

[英]OpenMP arbitrary reduction (merge)

I want to use OpenMP to collect some data.我想使用 OpenMP 收集一些数据。 For that, I check many candidates and collect only those that satisfy some conditions.为此,我检查了许多候选人并只收集满足某些条件的候选人。 The simplified example would be the following.简化示例如下。

#include <bits/stdc++.h>
#include "omp.h"

using namespace std;

class DataPoint {};

DataPoint random_data_point() {
    // generate random data point
}

bool test(DataPoint r) {
    // do something
}

int main() {
    constexpr int num_iterations = 10000;

    set<DataPoint> good_points;

#pragma omp parallel for reduction(???)
    for (int iter = 0; iter < num_iterations; iter++) {
        DataPoint r = random_data_point();
        if (test(DataPoint))
            good_points.insert(r);
    }

//  ...

    return 0;
}

The question is how to use OpenMP efficiently.问题是如何有效地使用 OpenMP。 My idea is that each thread collects its own data (in the example above - its own set) and then, after all of the thread finished, their sets are merged.我的想法是每个线程收集它自己的数据(在上面的例子中 - 它自己的集合),然后,在所有线程完成后,它们的集合被合并。

Note 1: my iterations are very independent (as in the example above), so OpenMP should be helpful.注 1:我的迭代非常独立(如上例所示),因此 OpenMP 应该会有所帮助。 Note 2: in the real programme, I use more complicated data structure than set.注2:在实际程序中,我使用了比set更复杂的数据结构。 (In fact, it is a convex hull of the data points.) (实际上,它是数据点的凸包。)

Modern OpenMP allows you to define your own reduction functions, so you should be able to achieve this that way should you want to, though, realistically, for something this simple it might be easier just to write code along these lines (untested, typed into this answer, not compiled :-))现代 OpenMP 允许您定义自己的归约函数,因此您应该能够以这种方式实现这一点,但实际上,对于如此简单的事情,只需按照这些行编写代码(未经测试,输入到这个答案,未编译:-))

#pragma omp parallel
{
    set<Data_Point> thread_good_points;
#pragma omp for nowait
    for (int iter = 0; iter < num_iterations; iter++) {
        DataPoint r = random_data_point();
        if (test(DataPoint))
            thread_good_points.insert(r);
    }
#pragma omp critical
    good_points.merge(thread_good_points);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM