Reputation: 4062
I just barely learned how to use a function in parallel. The following line of code calculates the square value of an index and places it in an array (called squares) at that index. The parallel_for function is available in Visual Studio 2010, as part of the Concurrency namespace under the header.
parallel_for(static_cast<size_t>(0), count,
[&squares](size_t n) { squares[n] = (n+1)*(n+1); });
You can see that it uses a lambda expression to calculate the squares in parallel, and this code does work and compile correctly. However, the lambda expression clutters the parallel_for function with code. I was thinking of just defining the lambda expression within a function object, for example:
function<void(size_t)> Squares =
[&squares](size_t n) { squares[n] = (n+1)*(n+1); };
My question is how can I use this function (Squares) within the parallel_for function? Did I write the Squares function incorrectly, or is this just a paradigm of the parallel_for to use lambda expression? You can go ahead and recommend some other parallel libraries to me other than Microsoft's, but I'd still like to know the answer to my question.
Upvotes: 3
Views: 1659
Reputation: 54178
Any lambda expression can be thought of as an anonymous version of the corresponding function object.
In your example, your functor works just fine, as below:
parallel_for(static_cast<size_t>(0), count, Squares);
From the MSDN docs:
A lambda expression is a programming technique that is related to anonymous functions. An anonymous function is a function that has a body, but does not have a name. A lambda expression implicitly defines a function object class and constructs a function object of that class type.
Upvotes: 3