简体   繁体   English

在parallel_for中使用函数对象

[英]Using function objects in parallel_for

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. 下面的代码行计算索引的平方值,并将其放在该索引的数组(称为square)中。 The parallel_for function is available in Visual Studio 2010, as part of the Concurrency namespace under the header. parallel_for函数在Visual Studio 2010中可用,作为标头下的Concurrency命名空间的一部分。

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. 您可以看到它使用lambda表达式并行计算平方,并且此代码可以正常工作和编译。 However, the lambda expression clutters the parallel_for function with code. 但是,lambda表达式将parallel_for函数与代码混为一谈。 I was thinking of just defining the lambda expression within a function object, for example: 我只想在函数对象中定义lambda表达式,例如:

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? 我的问题是如何在parallel_for函数中使用此函数(Squares)? Did I write the Squares function incorrectly, or is this just a paradigm of the parallel_for to use lambda expression? 我是否错误地编写了Squares函数,或者这只是parallel_for使用lambda表达式的范例? 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. 除了微软之外,您可以继续向我推荐其他一些并行库,但我仍然想知道我的问题的答案。

Any lambda expression can be thought of as an anonymous version of the corresponding function object. 任何lambda表达式都可以被认为是相应函数对象的匿名版本。

In your example, your functor works just fine, as below: 在您的示例中,您的仿函数工作得很好,如下所示:

parallel_for(static_cast<size_t>(0), count, Squares);

From the MSDN docs : 来自MSDN文档

A lambda expression is a programming technique that is related to anonymous functions. lambda表达式是一种与匿名函数相关的编程技术。 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. lambda表达式隐式定义函数对象类,并构造该类类型的函数对象。

MSFT的示例形式都直接使用Lambda。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM