I need to execute two parallel tasks using Intel Threading Building Blocks, and wait till both are finished.
I can do it as follows:
tbb::parallel_for( tbb::blocked_range<int>( 0, 2, 1 ), [&] ( const tbb::blocked_range<int>& range )
{
for ( int i = range.begin(); i < range.end(); ++i )
{
if ( i == 0 )
task0();
else if ( i == 1 )
task1();
}
} );
But I guess that tbb::parallel_for is not the best solution for this; is there a better/simpler method to achieve the same in TBB?
For a small number of tasks, you can use tbb::task_group
:
tbb::task_group g;
g.run([&] { task0(); });
g.run([&] { task1(); });
// do other work while tasks run ...
g.wait(); // wait for all tasks to finish
As a small optimization, can run one of the tasks in the current thread:
tbb::task_group g;
g.run([&] { task1(); }); // spawn a parallel task
task0(); // run one task in current thread
g.wait(); // wait for parallel task(s) to finish