0

I have a function that contains an OpenMP-parallelized for loop, which calls a callback at each iteration, similar to this:

template<class Callback>
void iterate(const Callback& callback, bool parallel) {
    #pragma omp parallel for if(parallel)
    for(int i = 0; i < 1000; ++i) {
        callback(i);
    }
}

The caller can control whether the loop is parallelized using the parallel argument. Is there a way to allow the caller to specify variables on which reduction should be done, like this:

int counter = 0;
#pragma omp ??? reduction(+ : counter)
iterate([&counter](int i) {
    counter++;
}, true);

One way seems to be to put #pragma omp parallel outside the function at the call site, and #pragma omp for inside the function. But this restricts how the function can be used, and seems to be non-standard.

Is there way to do this using nested parallel constructs, the loop contruct with its bind clause, or possibly another openmp feature?

9
  • std::atomic<int> might help here. Commented Jul 3 at 11:52
  • using atomics would be slower than reduction Commented Jul 3 at 11:53
  • It is not clear what you want to perform in the second part of the question nor why you talk about the first part since they are unrelated IMHO. Do you want the list of the reduced variable (i.e. counter) to be defined at runtime (and even de number/types)? Commented Jul 3 at 20:00
  • The for loop (with the pragma omp parallel for) is implemented inside of a function that returns to the caller via a callback. So its implementation is not accessible from the caller. But the variable that should be reduced is at the caller. Commented Jul 3 at 20:56
  • It should be possible to call iterate() at different places and with different callbacks, and do different reductions every time. (Not runtime-determined, but different for the different places where iterate() is used) Commented Jul 3 at 20:57

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.