在parallel_for中使用函数对象
我刚刚学会了如何并行使用函数。以下代码行计算索引的平方值并将其放置在该索引处的数组(称为 squares)中。 Parallel_for 函数在 Visual Studio 2010 中可用,作为标题下 Concurrency 命名空间的一部分。
parallel_for(static_cast<size_t>(0), count,
[&squares](size_t n) { squares[n] = (n+1)*(n+1); });
您可以看到它使用 lambda 表达式并行计算平方,并且此代码确实可以正确运行并编译。然而,lambda 表达式使 parallel_for 函数的代码变得混乱。我正在考虑在函数对象中定义 lambda 表达式,例如:
function<void(size_t)> Squares =
[&squares](size_t n) { squares[n] = (n+1)*(n+1); };
我的问题是如何在 parallel_for 函数中使用这个函数(Squares)?我是否错误地编写了 Squares 函数,或者这只是 parallel_for 使用 lambda 表达式的范例?您可以继续向我推荐除 Microsoft 之外的其他并行库,但我仍然想知道我的问题的答案。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
任何 lambda 表达式都可以被视为相应函数对象的匿名版本。
在您的示例中,您的函子工作得很好,如下所示:
来自 MSDN 文档:
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:
From the MSDN docs:
MSFT 的示例都直接使用 Lambda。
The examples form MSFT all use Lambda directly.