Can you give me an example on tbb "parallel_for" without using lambda expression? Because I can't run lambda expression under Ubuntu system's C++ compiler, and I don't why. to be brief: turn this for loop into parallel_for please.

void print(int n)
{
    cout<<n<<endl;
}
for(int i=0; i<100; i++)
{
    print(i);
}

by the way, if who can tell me how to run C++ lambda expression in linux system, that would be better for me. Thanks.

有帮助吗?

解决方案

parallel_for will take any functor, which can be a lambda, a functor class or a plain old function; the following should work just fine too:

#include "tbb/tbb.h"
using namespace tbb;
...
void print( size_t n) {
   printf("hellow world %d\n", n);
}
void print_range( const blocked_range<size_t> & r ){
     for( size_t i = r.begin(); i != r.end(); ++i )
         printf("hello from range: %d\n", i);
}
void doit() {
      parallel_for<size_t>( 1, 10, 1, print );
      parallel_for( blocked_range<size_t>(1,10), print_range );
}

其他提示

To use lambdas download gcc version 4.7 or later and give him option -std=c++11

#include "tbb/tbb.h"
using namespace tbb;
class ApplyFoo {
  float *const my_a;
  public:
    void operator()( const blocked_range<size_t>& r ) const {
      float *a = my_a;
      for( size_t i=r.begin(); i!=r.end(); ++i )
        Foo(a[i]);
    }
    ApplyFoo( float a[] ) :
      my_a(a) {}
  };
  void ParallelApplyFoo( float a[], size_t n ) {
  parallel_for(blocked_range<size_t>(0,n), ApplyFoo(a));
}

Source

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top