Search code examples
c++lambdatbb

Parallel reduce using lambda expressions


I am currently working on a function that takes in an array, size, low and high as parameters

parllelCount(int *src, int size, int low, int high)

The function returns the number of values from the source array that fall within the low and high range.

I have the following function that is making use of parallel reduce using lambda expression, but i am unable to figure out how the combine parameter in paralle_reduce should be implemented (commented in the snippet)

int parallelCount(int *src, int size, int low, int high)
{
    int counter = parallel_reduce(blocked_range<int>(0, size),
                                  int(0),
                                  [&](blocked_range<int> r, int counter)->int{
                                      for(int i = r.begin(); i < r.end(); i++){
                                          if(low <= src[i] && src[i] <= high){
                                              counter++;
                                          }
                                      }
                                      return counter;
                                  },
                                  //[](){}

    );
    return counter;
}

Solution

  • The combine presumably should just add up the results that the workers have computed, so something along the lines of

    [](int a, int b) { return a + b; }
    

    should work