Search code examples
parallel-processingc++17tbb

How does C++ parallel_reduce use the inital value parameter?


I expect the following code snippet to produce the sum of all the elements and the initial value but it doesn't:

    vector<long> a;
    a.resize(10);
    generate(a.begin(), a.end(), [n = 1]() mutable { return n++; });
#ifdef _MSC_VER
    sum = parallel_reduce(a.begin(), a.end(), 10);
    assert(sum == 65); // 11 * 5 + 10. It produces 215 instead.
#endif

Instead of the expected 65, it produces 215. Even if every element is added by 10, 31 * 5 = 155, not 215. How does 215 come about? What do I miss? Any reference that explains how the initial value is used is appreciated.


Solution

  • You did not really provide a MCVE as the code snippet in question does not compile, but one problem is still apparent: you assume the last argument to parallel_reduce is the initial value, while according to documentation it's identity value.

    Identity for addition is 0 and if you pass that, you will get expected result (55).