tbb parallel_for example c++ without lambda

Terry picture Terry · Jan 24, 2013 · Viewed 8.6k times · Source

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.

Answer

Rick picture Rick · Jan 25, 2013

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 );
}