Intel® oneAPI Threading Building Blocks
Ask questions and share information about adding parallelism to your applications when using this threading library.

Conditional parallelization



Does TBB provide a mechanism for conditional parallelization?

For example, assume the following code, and I want to parallelize this loop only when loopCount is larger than 1000 (if not, execute sequentially to avoid unnecessary parallelization overhead).

for( int i = 0 ; i < loopCount ; i++ ) { /* do something */ }

I want to do

if( loopCount > 1000 ) { parallel_for(...) { ... } } else { for(...) { ... } }

without replicating the loop body. It will be very nice if I have something like "parallel_for_if" :-)

Thank you very much,

0 Kudos
2 Replies
Black Belt
That's what grainsize is for (a parameter in the input Range). You want recursive parallelisation down to chunks that can be executed efficiently using serial optimisations like loop unrolling and vectorization, but that should work whether you start out with a number of elements that will never be subdivided or a really large number. Grainsize will be obeyed even with the (default) auto_partitioner, so you can try if it really improves matters (quite likely it won't). For a more complete picture, grainsize doesn't apply to tbb::parallel_sort, which will in fact check the number of elements and go straight to std::sort for a small-enough collection (or something to that effect), but sorting is inherently quite different from applying a map pattern, and each has to be considered on its own.
Black Belt

Continued in "parallel_sort".