A C++ lambda expression defined in a local variable to pass it to the parallel_for

Viewed 77

I'm trying to implement a conditional (size-depending) processing of std::vector. If it should be processed in serial mode on a single thread, I simply call a function defined as lambda expressin within a plain 'for' loop, and it works OK. But when I tried to pass that lambda function as an argument to the concurrency::parallel_for (after '#include <ppl.h>'), it can't compile saying theres' no matching function to call the 'parallel_for'.

    Array3<T> res = this->cloned();
    size_t imax = res.getCount();

    // my lambda expression to process elements of std::vector
    std::function<void(size_t)> lambdaFun = [&](size_t i) {
        res[i] *= rhs[i]; 
    };
    
    size_t i;

    if (ll())
    {
        // ll job
        concurrency::parallel_for(size_t(0), imax, lambdaFun); // fails to compile
    }
    else 
    {
        // serial job
        for (i = 0; i < imax; i++)
        {
            lambdaFun(i); // works great
        }
    }

However, when I pass a body of that lambda function to the 'concurrency::parallel_for' directly, it works:

concurrency::parallel_for(size_t(0), imax, [&](size_t i)
            {
                res[i] *= rhs[i];   // the same code as it was in the lambda works OK
            }
        );

I tried to change the type of a local variable storing the lambda function this way:

auto lambdaFun = [&](size_t i) 
    {
        res[i] *= rhs[i];
    };

But it did not help.

So the question is: how to properly pass the lambda function defined in local variable 'lambdaFun' to 'parallel_for' without expicitly typing contents of its body in the loop?

1 Answers

Thanks to you all!

Finally I get it worked. The counter size_t i was declared gobally in the member method, that is why my lambda has presumably treated the counter being not appropriate for what the parallel_for expects.

Also I decided to leave the function type as auto.

The right code is here:

Array3<T> res = this->cloned();
    size_t imax = res.getCount();

    auto lambdaFun = [&](size_t i) {
        res[i] *= rhs[i];
    };

    if (res.ll())
    {
        // ll job
        concurrency::parallel_for(size_t(0), imax, lambdaFun);
    }
    else
    {
        // serial job
        for (size_t i = 0; i < imax; i++)
        {
            lambdaFun(i);
        }
    }
Related