reduce_parallel 是不是线程安全函数?

reduce_parallel is not a thread-safe function?

我想调用parallel_reduce对向量元素求和。但是我发现如果向量元素足够了,结果是不正确的。请帮助我如何使用此功能。

// prepare data
    const size_t allNum = 1000000;
    std::vector<double> a;
    for (int i = 0; i < allNum; ++i)
    {
        a.push_back(double(i + 1));
    }

    // λ func
    auto f = [&]() -> double {
        return tbb::parallel_reduce(tbb::blocked_range<size_t>(0, allNum), 
            0.0,
            [&](const tbb::blocked_range<size_t>& r, double init) -> double {
            for (int i = r.begin(); i < r.end(); ++i)
            {
                init += a[i];
            }
            return init;
        },
            [](double f, double s) -> double {
            return f + s;
        }
            /*std::plus<double>()*/);
    };

    // call λ func, get the result
    double correctResult = (1.0 + 1000000.0) * 500000.0;
    double sum = f(); // sum != correctResult
    // sum is different every loop

我试过运行上面的代码。它工作正常,也得到了正确的结果!

有关parallel_reduce的更多信息,请参阅以下链接: https://software.intel.com/content/www/us/en/develop/documentation/tbb-documentation/top/intel-threading-building-blocks-developer-reference/algorithms/parallelreduce-template-function.html

https://link.springer.com/content/pdf/10.1007%2F978-1-4842-4398-5.pdf

谢谢, 桑托什